window.onbeforeunload event is not working for the first time, when we
reload the url no alert coming while closing the browser tab.
但是当我们触摸页面上的任何元素并关闭选项卡时,它就会起作用。
$(document).ready(function(){
window.onbeforeunload = function (event) {
var message = 'Important: Please click on \'Save\' button to leave this page.';
if (typeof event == 'undefined') {
event = window.event;
}
if (event) {
event.returnValue = message;
}
return message;
};
$(function () {
$("a").click(function () {
window.onbeforeunload = null;
});
});
});
答案 0 :(得分:0)
这是某些浏览器上的预期行为。如here所述:
To combat unwanted pop-ups, some browsers don't display prompts created in beforeunload event handlers unless the page has been interacted with. Moreover, some don't display them at all.
实质上,这是为了防止网页被滥用。