简体   繁体   中英

beforeunload getting called on page refresh and href clicks

I am using the following function to detect browser close, or someone types some other website name etc,

$(window).bind("beforeunload", function(){
        return confirm("Do you really want to close?"); 
    });

But the above code is getting called for page refresh, href clicks, form submits etc

how can retrict not to run the above code in these scenarios, or am i missing some other method

any help or pointers to code will be appreciated

beforeunload gets called before the current page is being unloaded no matter where the next destination is - any other page, even on your own site,even a reload of the current URL. The idea behind the function is to be able to ask the user about unsaved data in this particular web page so it's triggered when anything that might cause that data to be lost is about to happen.

According to the mozilla docs , there is no standard for this method. It was implemented by IE4 and copied by other browsers.

I don't see any way to know why the page is about to be closed. Usually, the way this is used is that the page keeps track of some sort of changeflag and only prompts the user if they have important, unsaved data.

Here's Microsoft's documentation on the event data that comes this event. You will have to devise some tests to see if you can reliably tell (across browsers) what is causing this to get called and avoid your prompt in some cases.

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