开发者

Chrome/Safari not calling unload in some cases

开发者 https://www.devze.com 2023-02-13 07:58 出处:网络
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 use

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.


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
    });
};


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.
};
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号