'JSF p:remoteCommand and javascript event onbeforeunload

We have several web applications a user can login. On click on logout button some logic must be processed. The problem is that most users close the browser without clicking on logout button. I tried the following to call my logic on browser close:

  1. Added the event "onbeforeunload" to my frameset. On browser close a logout function will be called.
  2. Within my logout function I use the primefaces p:remoteCommand component to call a action listener on the server.

In current firefox version everything works fine but I have some problems with IE9. Closing a tab in IE9 calls my logic. Closing the browser doesn´t work. My JS function is called but the request to the server is not executed. Is there any way to solve this problem? BTW: I know that this is not an 100% solution but we need exactly this functionality. My function and p:remoteCommand looks like that.

function automaticLogout() {
    handleAutomaticLogout();
    alert('BlaBla');
}

<p:remoteCommand name="handleAutomaticLogout" actionListener="#{myBean.handleAutomaticLogout}" async="false" />


Solution 1:[1]

Do you specifically require a client-side Javascript solution or is this just the way you have gone about it so far?

On the Server Side, placing a @PreDestroy annotation above a Backing Bean method causes that method to be invoked just before the Bean goes out of scope.

If you write a method which invalidates the session (session.invalidate()) with this annotation, it will be called when the user leaves your page without clicking Log Out.

Backing Bean:

import javax.annotation.PreDestroy;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.SessionScoped;
import javax.faces.context.FacesContext;
import javax.servlet.http.HttpSession;

@ManagedBean
@SessionScoped
public class PreDestroyBean {

    //Called by button - log out perhaps?
    public void killTheSessionDeliberately() {
        HttpSession session = (HttpSession) FacesContext.getCurrentInstance().getExternalContext().getSession(false);
        session.invalidate();
    }

    @PreDestroy
    public void revokeLicense() {
        System.out.println("PreDestroy method was called.");

    }
}

Page Button:

<h:form>
    <p:commandButton id="killSession" value="Kill Session" 
            actionListener="#{preDestroyBean.killTheSessionDeliberately()}" update="@form" />
</h:form>

Solution 2:[2]

You can use p:remoteCommand along with onunload. example:

<body onunload="test();"> 
    <form id="exit">
       <p:remoteCommand  id="test" name="test" action="#{ContatoMB.teste}"/>
    </form>
</body>

referencing http://forum.primefaces.org/viewtopic.php?f=3&t=15695 It works for me.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1
Solution 2 wolf97084