Showing posts with label How to read Liferay's URL via script. Show all posts
Showing posts with label How to read Liferay's URL via script. Show all posts

Monday, 23 February 2015

How to read Liferay's URL parameter via script

Steps to read Liferay URL parameter via script.

1) Add a tag in your .JSP to read portlet namespace
<%@ taglib uri="http://java.sun.com/portlet_2_0" prefix="portlet" %>

2) Create a global script variable inside your JSP for portlet name space
<script type="text/javascript" charset="utf-8">
var portletNamespace ='<portlet:namespace/>';
</script>

In a js file we can not use '<portlet:namespace/>' directly, hence we need to create a global js variable which can be accessed in .js file.

3) Create a function which reads and returns the URL parameter
function getURLParameterValue(parameterName, url) {
parameterName = parameterName.replace(/[\[]/, '\\\[').replace(/[\]]/, '\\\]');
var results = new RegExp('[\\?&]'+parameterName+'=?([^&#]*)').exec(url || window.location.href);
return results == null ? null : results[1];
}

Here, function accepts two values
#1) "parameterName" whose value needs to be read (This is an actual name from the URL parameter)
#2) "url" (Its an href location / window's current URL)

4) Read the URL in the javascript function
Let's say this is your URL :     <protocol>://<hostname>:<port>/group/control_panel/manage?p_auth=asdfg&p_p_auth=xyz&p_p_id=_sometext_WAR_sometextportlet_&p_p_lifecycle=1&p_p_state=maximized&p_p_mode=view&doAsGroupId=12345&refererPlid=5555&_sometext_WAR_sometextportlet_id=123456

Ex: Read Liferay Parameter
>) getURLParameterValue(portletNamespace + "id", window.location.href)
will return "123456"
Ex: Read Any parameter without portletNamespace prefixed
>) getURLParameterValue("p_auth", window.location.href) 
will return "asdfg"

Cheers!
Henal Saraiya
(Senior Consultant)
CIGNEX Datamatics