简体   繁体   中英

Is there a way to detect closing page by javascript?

I watched a few threads here,mostly used this: window.onbeforeunload = function (e) { var e = e || window.event;

//IE & Firefox if (e) { e.returnValue = 'Are you sure?'; }

// For Safari return 'Are you sure?'; };

but seems this will mix the situation of refreshing page and close page, is there any possibility to distinguish these two situations?

function OnUnLoad()
{
    if (window.event.clientY < 0 && window.event.clientX < 0)
    {
        //cleanup code goes here...
    }       
}

This seems to work for me on all browsers. But closing tabs seems to cause issues. Actually, there is not "documented" way of doing it.

There isn't really a way to differentiate the two different events in Javascript. You can take the GMail approach and use AJAX for everything, so as to never cause a page reload. This means the only time "OnBeforeUnload" is called is when the use is actually leaving the page. The alternative is to put JS on all your links to disable the OnBeforeUnload script when they click on a link, but you only want the even to fire when the browser actually closes.

As far as the browser is concerned, there isn't any difference between the user clicking on a link to navigate away from your page, and clicking on the browser close button.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM