Client-Side Inter-Portlet Communication with simple Javascript
This guide shows how two portlets can exchange information using mere javascript functions. This is a "quick-and-dirt" way of communication, for a more standard solution you should use Public Render parameters or Events. Some description of these methods and the correspondent examples can be found here JSR 286 Interportlet Communication
For the example we will define two portlets, a Sender and a Receiver. The Sender will be able to call a javascript function defined by the Receiver, which will update a label defined in the presentation view.
To use this type of communication, we just need to include the Javascript functions and calls in the JSP view of the portlet.
Step 1: Define the Javascript function
<script type="text/javascript">
var Receiver = {};
Receiver.displayMessage = function(sender, message) {
document.getElementById("text").innerHTML += "Received message: "
+ message + " from: <" + sender + "> <br/>";
};
</script>
- Line 2: We define an object that will act as an artificial "namespace". This is not mandatory but recommended for clarity.
- Line 4: We define a function inside the namespace object. In this example the function receives two parameters, the sender of the message and the message itself.
- Line 5: What the function does is up to the developer. In this example it just updates a label in the view of the portlet that contains the id of the sender and the message passed.
Step 2: Invoking the Javascript function from other portlet
Once the Receiver portlet is set up, we already can invoke the function from any other portlet present in the same page of the portal. For that we use the namespace object we have defined and the correspondent function signature.
<button type="button"
onclick="Receiver.displayMessage('<portlet:namespace/>','hello');">Send
hello message - javascript!</button>
- We have defined a button which defines the 'onclick' event as a call to the javascript function with the portlet namespace and the message hello
Remarks
- This is an easy way to communicate two portlets by sharing javascript functions.
- Depending on the desired functionality there might be problems if many instances of the portlet are active in the same page.
Source code
The source code of the two portlets that communicate using javascript function and also a simple standard portlet event can be downloaded here:
Instructions (maven based)
- Check out the code of both portlets.
- Change the property <liferay.auto.deploy.dir> in the pom.xml to your current portlet deploy directory.
- In the main folder of each portlet run maven: clean install liferay:deploy.
- Add the portlets to your portal GUI and try them out!





