Using HTML5 Notification API in XPages

HTML5 introduces Web Notifications API which “allows alerting the user outside the context of a web page of an occurrence, such as the delivery of email“. This opens up quite a few possibilities for developers like alerting a user when a document needs approval irrespective of the XPage he is currently on.

In this example I will use the Extension Library control Remote Service to poll a view to check if any documents require approval and if yes then show notification to user.

Remote Service control

The Remote Service control allows calling SSJS code from client side JavaScript code without a full page refresh. Instead the output of the SSJS code is returned asynchronously. Tim Tripcony gave a beautiful explanation here on how this control should be used and its usage scenarios.

You can find the Remote Service control under Data Access group in your Control view. Drag it on to your XPage.

Set the properties for Remote Service as displayed below.

Notice the value of property serviceName. We will be using this property in our client side JavaScript code call the remote method. In the script property of remote method we will write the SSJS script which will be checking if there is any document with Status as “Submitted” and return the count of those documents. So our code for remote service would be:

Now we call our remote service at regular intervals and notify the user if there are any documents to approve. Here I am checking every 5 seconds (which would not be suitable for production).

Web Notification API

This article on Mozilla Developer Network describes how to use the notification API. First we check if the browser supports notifications API by this statement.

If the browser supports it then we ask for permission from user to show notifications.

So our function notifyUser would come to something like this:

To create notification we call the following statement:

So our createNotification would be this:

We store the image notificationicon.png, shown in above code snippet, in our database itself as file (or image) resource. Now when you open your XPage you would get notifications in browser in case you have documents pending for approval.

Notifications as shown in Google Chrome and Firefox respectively

Notifications as shown in Google Chrome and Firefox respectively

The above demo only works in latest versions of Google Chrome and Mozilla Firefox.

Putting everything together

We put the entire code together and our XPage looks like this.

You can also download the demo database and try it out: Notification Demo.


2 thoughts on “Using HTML5 Notification API in XPages

Leave a Reply

Your email address will not be published. Required fields are marked *