How to identify browser tab closing using javascript or jquery?

爱⌒轻易说出口 提交于 2020-01-03 02:56:36

问题


How to identify browser tab closing using javascript or jquery? I have to give a confirmation message when user click on the browser close button. If user press yes button I have to load another page on the same tab. if press cancel. then close the tab. any body knows the scripts for this functionality. Please help me :(


回答1:


Try something like this:

$(window).unload(function() {
    var bye = confirm("Go away?");
    if (bye) {
       // do stuff
       window.location = "http://somewhere_else";
    } else {
       // do stuff?
       // stay here
    }
});



回答2:


That's annoying as hell from a user experience perspective IMO, but you can try using the onunload event:

$(window).unload(function() {
    if(confirm("Load something else here?")) {
        // blah blah blah
    }
});



回答3:


onbeforeunload = function() {
   return 'string';
}

would give a prompt. you can also insert a modal through:

onbeforeunload = function() {
   var x = window.open('file.html');
}

you can't really customize it per how you want it, it's locked down by the browser.




回答4:


This site uses onbeforeunload. You can play around with it and see if it does what you need. Type in some text into the answer box and try to refresh, navigate away, close tab, close browser.



来源:https://stackoverflow.com/questions/3261900/how-to-identify-browser-tab-closing-using-javascript-or-jquery

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!