javascript 在窗口关闭时触发函数

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/12158190/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-26 15:28:24  来源:igfitidea点击:

Fire a Function on window close

javascript

提问by sv_in

Possible Duplicate:
javascript detect browser close tab/close browser

可能重复:
javascript 检测浏览器关闭选项卡/关闭浏览器

I have a java script countdown timer on my page and i want to trigger an alert message if user tries to close the window or a tab.

我的页面上有一个 java 脚本倒数计时器,如果用户尝试关闭窗口或选项卡,我想触发警报消息。

回答by sv_in

https://developer.mozilla.org/en-US/docs/DOM/window.onbeforeunload

https://developer.mozilla.org/en-US/docs/DOM/window.onbeforeunload

Update: this answer was provided by Adnan in comment few mins before me :)

更新:这个答案是 Adnan 在我几分钟前的评论中提供的 :)

回答by RAKESH HOLKAR

Use this event

使用此事件

window.onbeforeunload = function() {
   //your message goes here
}

By using jQuery

通过使用 jQuery

$(window).unbind("beforeunload");
$(window).bind("beforeunload", function (e) {
   //do your work here
});