简体   繁体   中英

Beforeunload event does not fire after page refresh Chrome

I have this simple code

 <!DOCTYPE html> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <title></title> <!--<script src="angular.min.js"></script>--> <script> window.onload = function () { window.addEventListener("unload", function () { debugger; }); window.addEventListener("beforeunload", function () { debugger; }); window.onbeforeunload = function () { } } </script> </head> <body ng-app="app"> </body> </html> 

I want unload or beforeunload events be fired after I refresh the page. This is not happening in Chrome Versión 67.0.3396.62. I have tried firefox and edge and it works well. It also works when i close the tab. The error ocurrs only when i refresh the page.

You've run into an issue that was already reported. It looks like a bug, but according to a Chrome dev (kozy) it is a feature :

Thanks for repro. It is actually feature. As soon as you pressed reload we ignore all breakpoints before page reloaded. It is useful all the time when you have a lot of breakpoints and need to reload page to restart debugging session.

Workaround: instead of pressing reload button you can navigate to the same url using omnibox then all breakpoint will work as expected.

I've added bold emphasis to point out the workaround proposed by kozy. I've tried it and found that it works.

Other than the issue with the debugger statement, the handlers are executed whether you are reloading or closing the tab. In both cases that follow, I get the stock prompt that Chrome provides when returning true:

window.addEventListener("beforeunload", function (ev) {
  ev.returnValue = true; // `return true` won't work here.
});

This works too:

window.onbeforeunload = function () {
  return true;
}

It used to be that you could use a return value with a message and the browser would show your custom message but browsers generally no longer support this.

Whether or not you want to set the handler for beforeunload inside a handler for load is entirely dependent on your goals . For instance, I have an application for editing documents that does not set the beforeunload handler until the application has started initializing, which is much later than the load event. The beforeunload handler is there to make sure the user does not leave the page with unsaved modifications.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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