Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Chrome/Safari not calling unload in some cases

Have been stuck with this issue for a few days now, and really need, and would appreciate some help. My requirement is that I want to make a server side callback to clear off some objects when the user navigates away from our page, without clicking logout. For business reasons, our ASP.NET session timeout has to be set to a very high value. Further, I do not want to popup a alert/dialog to force the user to return to the page and click Logoff.

The solution I have arrived at thus far is to make a AJAX callback by embedding this javascript in the page.

window.onunload = pageleave;
     function pageleave() {                  
                  alert('test');
                  PageMethods.CheckLogout('abc','xyz',OnSucceed,OnFail);                  
      }     

Here is the problem though : For IE and Firefox, the unload fires, the alert is seen, and I see the callback on my C# side in all the cases I desire

    a)  User closes browser 
    b)  User types in a new URL in the address bar 
    c)  User clicks on a link causing page to reload

For Chrome and Safari, cases a and b work fine. However, when the user clicks on a link, which causes my aspx page to reload, my C# side code is not invoked. The javasacript alert is fired though.

I am trying to see how I can get Chrome/Safari to behave like IE/Firefox. Is this even a possibility?

Thanks in advance for the help,

Rajesh.

like image 674
mattr Avatar asked Feb 26 '11 02:02

mattr


2 Answers

Use the beforeunload event instead of the unload event.

Also, use a synchronous AJAX request, not an asynchronous one, so that the request is completed before your beforeunload function exits.

I'm not sure how you would do a synchronous AJAX request using your JavaScript framework. In jQuery, it would look like this:

window.onbeforeunload = function() {
    jQuery.ajax({
        url: '/page/to/load',
        async: false
    });
};
like image 163
Mark Eirich Avatar answered Oct 11 '22 15:10

Mark Eirich


In case anyone comes across this in the future, I couldn't use window.onbeforeunload as it was firing too early. Instead, I found window.onpagehide as a suitable workaround.

e.g.

window.onpagehide = function() {
    // some code here.
};
like image 25
wislam Avatar answered Oct 11 '22 15:10

wislam