onbeforeunload not working when a window is being closed

6,845 views
Skip to first unread message

Ryan Kang

unread,
Mar 20, 2019, 4:59:03 AM3/20/19
to Chromium-discuss
Hi,

I was testing if I can stop the browser from closing when the x button is clicked by using the code below. But, it doesn't work. I assume the browser doesn't wait until this script is triggered. Is there any way that I could accomplish stopping the browser from closing? I eventually would like to run ajax call before closing the browser.


window.onbeforeunload = function(){
  //do something
  return 'test';
};


Thanks,
Ryan

PhistucK

unread,
Mar 20, 2019, 5:01:00 AM3/20/19
to rkang....@gmail.com, Chromium-discuss
Works for me when I try it.
Note that the user must interact with the page somehow (clicking somewhere) before closing its window, otherwise beforeunload is ignored in order not prevent abuse.

PhistucK


--
--
Chromium Discussion mailing list: chromium...@chromium.org
View archives, change email options, or unsubscribe:
http://groups.google.com/a/chromium.org/group/chromium-discuss

---
You received this message because you are subscribed to the Google Groups "Chromium-discuss" group.
To unsubscribe from this group and stop receiving emails from it, send an email to chromium-discu...@chromium.org.

Ryan Kang

unread,
Mar 20, 2019, 8:35:08 AM3/20/19
to PhistucK, Chromium-discuss
Hi PhistucK,

Thanks for your reply. It didn't work when I tried it on chrome (Version 73.0.3683.75).

Ryan

PhistucK

unread,
Mar 20, 2019, 8:55:20 AM3/20/19
to Ryan Kang, Chromium-discuss
Then it might be some coding issue. If you run the same code from the website (in the console, for example), does it work?

PhistucK

Ryan Kang

unread,
Mar 20, 2019, 9:11:50 AM3/20/19
to PhistucK, Chromium-discuss
Hi PhistucK,

Thanks for the prompt reply. Yes, it works if I put the code in the console but it doesn't work when I put the code in the html file. (please see below)


<!DOCTYPE html>
<html>
<head>
  <title>test</title>
</head>
<body>
<script type="text/javascript">
window.onbeforeunload = function(){
return 'here';
};
</script>
</body>
</html>

arthurs...@chromium.org

unread,
Mar 20, 2019, 9:18:58 AM3/20/19
to Chromium-discuss, phis...@gmail.com
Hi Ryan,

I tried to put your code in an index.html file and opened it.
1. If I don't interact with the document, the beforeunload is not called.
2. If I interact with the document, the beforeunload is called.

Make sure you tried to click on the document before closing the tab.

To me, it seems to work as intended. Feel free to open a bug on https://crbug.com if you think otherwise.
Reply all
Reply to author
Forward
0 new messages