Run JavaScript code on window close or page refres

2018-12-31 16:56发布

Is there a way to run a final JavaScript code when a user closes a browser window or refreshes the page?

I'm thinking of something similar to onload but more like onclose? Thanks.

I don't like the onbeforeunload method, which always yields to a confirmation box popping up (leave page/ stay on mozilla) or (reload/ don't reload on chrome). Is there a way to execute the code quietly?

8条回答
唯独是你
2楼-- · 2018-12-31 17:16

There is both window.onbeforeunload and window.onunload, which are used differently depending on the browser. You can assing them either by setting the window properties to functions, or using the .addEventListener:

window.onbeforeunload = function(){
   // Do something
}
// OR
window.addEventListener("beforeunload", function(e){
   // Do something
}, false);

Usually, onbeforeunload is used if you need to stop the user from leaving the page (ex. the user is working on some unsaved data, so he/she should save before leaving). onunload isn't supported by Opera, as far as I know, but you could always set both.

查看更多
倾城一夜雪
3楼-- · 2018-12-31 17:18

jQuery version:

$(window).unload(function(){
    // Do Something
});

Update: jQuery 3:

$(window).on("unload", function(e) {
    // Do Something
});

Thanks Garrett

查看更多
长期被迫恋爱
4楼-- · 2018-12-31 17:22

The event is called beforeunload, so you can assign a function to window.onbeforeunload.

查看更多
心情的温度
5楼-- · 2018-12-31 17:23

You can try something like this:

<SCRIPT language="JavaScript">
<!--
function loadOut()
{
window.location="http://www.google.com";
}
//-->
</SCRIPT>

<body onBeforeUnload="loadOut()">
查看更多
泛滥B
6楼-- · 2018-12-31 17:26

You can use window.onbeforeunload.

window.onbeforeunload = confirmExit;
function confirmExit(){
    alert("confirm exit is being called");
    return false;
}
查看更多
公子世无双
7楼-- · 2018-12-31 17:27

The documentation here encourages listening to the onbeforeunload event and/or adding an event listener on window.

window.addEventListener('beforeunload', function(event) {
  //do something here
}, false);

You can also just populate the .onunload or .onbeforeunload properties of window with a function or a function reference.

Though behaviour is not standardized across browsers, the function may return a value that the browser will display when confirming whether to leave the page.

查看更多
登录 后发表回答