Event to be triggered when leaving website or closes the browser

瘦欲@ 提交于 2019-12-13 03:18:26

问题


I´m trying for a while execute a javascript function when a user leaves web site by typing a address in the browser and hits return or the user closes the brower clicking in the 'x' button.

I tried the unload event but I cannot get the alert

this is what I am doing:

$(window).unload(function () {
    alert("Are you sure?");
});

also

$(body).unload(function () {
    alert("Are you sure?");
});

I am running out of idea!


回答1:


You can listen to beforeunload event that fires before the unload event, when the page is unloaded.

$(window).on('beforeunload', function(){
    // ...
})



回答2:


Some browsers (like Chrome) block alerts in unload event handlers, to prevent exactly these kind of annoying messages. Try a console.log or put a breakpoint in to find out if the handler is triggered when you don't have an alert there.

SO question on a similar line:

window.onunload is not working properly in Chrome browser. Can any one help me?

You can only pass the alert by returning a string in a beforeunload handler (HT @undefined), but I would avoid even that, because popups are generally bad, and most people will do minimum processing to work out the make-this-thing-go-away option before they actually think about the contents of the box.




回答3:


The function you defined in window.onbeforeunload if it returns a string it will pop up a confirm navigation prompt with that message.

Alerts may be ignored!

window.onbeforeunload = function() {
    return "All unsaved data will be lost. Are you sure?";
};

Some browsers handle the onbeforeunload differently. Recent Firefox for example will ignore your return string and just display a standard message.




回答4:


$(window).bind('beforeunload', function(){
    alert("Are your sure?")
});


来源:https://stackoverflow.com/questions/13647314/event-to-be-triggered-when-leaving-website-or-closes-the-browser

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