Detect browser close event

你说的曾经没有我的故事 提交于 2021-01-28 15:16:31

问题


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
How to capture the browser window close event?
javascript detect browser close tab/close browser
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. But unfortunately I could not succeed. The onbeforeunload and onunload methods are also not working.

Any help will be highly appreciated. Thanks


回答1:


You cannot show an alert() on an onbeforeunload. You need to return to show a 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 onbeforeunloadOR return myUnloadEvent(); It depends what you are trying to do inside onbeforeunload. Try not to make any AJAX call as the browser may not run the script. You can unset web storage varibles, delete session, etc.

Also beware that this event will also fire when you refresh the page.




回答2:


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:

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

But if you use a console.log command, it will go through.



来源:https://stackoverflow.com/questions/30449668/detect-browser-close-event

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