Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to execute something inside window.onbeforeunload = function(e) {..} in Chrome?

As mentioned by LapinLove404 in window.onbeforeunload not working in chrome, it seems that in Chrome inside the beforeunload function, it's not possible to do anything else than changing the confirmation message.

The following code works in FF and IE, but doesn't in Chrome:

<html>
<head>
<script type="text/javascript">
 window.onbeforeunload = function sair() {
  alert("This alert doesn't show up in Chrome");
  return "If you leave this page your data will be lost!";
 }
</script>
</head>
<body>
 <a href="http://www.example.com"> Leave the page </a>
</body>
</html>

How could I do something before the user leaves the page? For example, if I needed to save the page state with an asynchronous call or unset a previously set lock. I think there are many use cases for it, but unfortunately Chrome doesn't make it a trivial task. Any ideas for a workaround?

like image 332
Saul Berardo Avatar asked Jul 12 '26 16:07

Saul Berardo


1 Answers

The functionality of onbeforeunload is very limited. I think the most you can do is return a message. You can not stop someone from leaving your page. You can't execute any code in an onbeforeunload. You could try onunload for that.

like image 122
Halcyon Avatar answered Jul 14 '26 04:07

Halcyon