According to HTML5 page visibility API, it is useful to develop power efficient web applications. Here is an excellent demo written by Sam Dutton.

In the upcoming ZK 6.5.1, we implemented this API with onVisibilityChange event which is easy to use. Here is a very simple sample:

        if (!event.isHidden())
            lbl.setValue("Welcome back");

We can also use it with Server Push too, here I use chat room as an example. In the sample we assume two users are in the chat room, when first user leaves the chat room temporarily (first user’s browser page is hidden), second user’s browser page will show a notification which says that the first user left. When first user comes back (first user’s browser page is visible), second user’s browser page will show a notification that says first user is now back. Here are the code snippet:
1. The simple zul page.


2. Listen onVisibilityChange event to root component and publish an event.

@Listen("onVisibilityChange = #win")
public void changeVisibility(Event event) {
    VisibilityChangeEvent evt = null;
    if (event instanceof VisibilityChangeEvent) {
        evt = (VisibilityChangeEvent) event;
        EventQueue que = 
          EventQueues.lookup("visibility", EventQueues.APPLICATION, true);
        String username = user.getValue();
        if ("".equals(username))
            username = "Unknow user";
        Map data = new HashMap();
        data.put("username", username);
        data.put("status", evt.isHidden() ? " Leaved" : " Come back");
        que.publish(new Event("onShowNotification", null, data));

3. Subscribe the event and show the notification.

@Subscribe(value="visibility", scope=EventQueues.APPLICATION)
public void showNotification(Event event) {
    Map data = event.getData();
    String username = data.get("username");
    if (!username.equals(user.getValue())) {
        String message = data.get("username") + data.get("status");
        Clients.showNotification(message, "info", null, null, 1500);

Normally, we can only get user status by checking session, with HTML5 Page Visibility API, we don’t need to save lot of information in session anymore.

Download whole sample code from github.

In ZK PE/EE, comet server push also supports this API to reduce server loading by default.

HTML5 page visibility API
HTML5 page visibility API demo
ZK Developer Reference – Browser Page Visibility State

If you enjoyed this post, please consider leaving a comment or subscribing to the RSS feed to have future articles delivered to your feed reader.

Leave a Reply