简体   繁体   中英

window.onbeforeunload not working properly after postback/page load

I've got this simple function that prevents users to accidentally close browser pages (in my case on chrome) prompting a confirmation message.

window.onbeforeunload = function () {
    return "Are you sure you want to leave this page?";
};

It works all fine but i found some limitations:

  • on page load the function doesn't work if you first don't interact with the page in some way
    eg click somewhere in the DOM

This behavior is particularly annoying inside the classic asp net application (web page) that loads data from a DB into a gridview because every time data is loaded the postback appends and if you close the tab no confirmation message appears. (i know you can use UpdatePanels to avoid the postback, but it's not the solution i'm looking for)

I tried to generate a click on some element of the DOM on page load:

$('#someID').click();

but didn't work.

Any ideas?

According to https://developer.mozilla.org/en-US/docs/Web/API/WindowEventHandlers/onbeforeunload :

You can and should handle this event through window.addEventListener() and the beforeunload event. More documentation is available there.

The linked articles go on to state:

WebKit-based browsers don't follow the spec for the dialog box. An almost cross-browser working example would be close to the following:

 window.addEventListener("beforeunload", function (e) { var confirmationMessage = "\\o/"; e.returnValue = confirmationMessage; // Gecko, Trident, Chrome 34+ return confirmationMessage; // Gecko, WebKit, Chrome <34 }); 

try using $('#someID').focus() instead of $('#someID').click().

$(document).ready(function () {
$('#someID').focus();
});

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