简体   繁体   English

检测浏览器关闭事件

[英]Detect browser close event

I want to capture the browser window/tab close event. 我想捕获浏览器窗口/选项卡关闭事件。 I have tried the following But not working: 我已经尝试了以下方法,但是没有用:

<script type="text/javascript">
window.onbeforeunload = function(){ myUnloadEvent(); }
function myUnloadEvent() {
    alert ('Calling some alert messages here');
}
</script>
<body>
Body of the page goes here.
</body>

Tried these links also but no more success. 尝试了这些链接,但没有成功。

javascript to check when the browser window is close javascript检查浏览器窗口何时关闭
How to capture the browser window close event? 如何捕获浏览器窗口关闭事件?
javascript detect browser close tab/close browser javascript检测浏览器关闭选项卡/关闭浏览器
Trying to detect browser close event 尝试检测浏览器关闭事件

Problem : 问题:

I just want to detect the browser close event and do some handling on that without showing the prompt to the user. 我只想检测浏览器关闭事件并对其进行一些处理,而不会向用户显示提示。

I have tried many methods to detect browser close event through jQuery or JavaScript. 我尝试了许多方法来通过jQuery或JavaScript检测浏览器关闭事件。 But unfortunately I could not succeed. 但是不幸的是我无法成功。 The onbeforeunload and onunload methods are also not working. onbeforeunload和onunload方法也不起作用。

Any help will be highly appreciated. 任何帮助将不胜感激。 Thanks 谢谢

You cannot show an alert() on an onbeforeunload . 您不能在onbeforeunload上显示alert() You need to return to show a confirm dialog . 您需要return以显示confirm dialog

<script type="text/javascript">
window.onbeforeunload = function(e){  
  return 'Calling some alert messages here'; //return not alert
}
</script>
<body>
Body of the page goes here.
</body>

Also do not call a function like that, write directly in the onbeforeunload OR return myUnloadEvent(); 也不要调用类似的function ,直接在onbeforeunload编写或return myUnloadEvent(); It depends what you are trying to do inside onbeforeunload . 这取决于您要在onbeforeunload内部执行的操作。 Try not to make any AJAX call as the browser may not run the script. 尝试不要进行任何AJAX调用,因为浏览器可能无法运行该脚本。 You can unset web storage varibles, delete session, etc. 您可以取消设置Web存储变量,删除会话等。

Also beware that this event will also fire when you refresh the page. 另请注意,刷新页面时也会触发此事件。

You can see the console quickly write that line before the screen closes. 您可以看到控制台在屏幕关闭之前快速写了该行。

window.onbeforeunload = myUnloadEvent;
function myUnloadEvent() {
    console.log("Do your actions in here")
}

Alerts are not allowed during beforeunload - if you have Preserve log switched on you will see this: 在beforeunload期间不允许出现警报-如果您打开了Preserve日志,则会看到以下信息:

Blocked alert('Calling some alert messages here') during beforeunload.

But if you use a console.log command, it will go through. 但是,如果使用console.log命令,它将通过。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM