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.
Quote: The beforeunload event is fired when the window, the document and its resources are about to be unloaded. However, for your requirement you could use a cookie or a local storage to know if it was a page refresh or close.
Deprecated. Not for use in new websites.
1) It refuses to call all blocking native functions (alert, prompt, confirm). It is obvious from User perspective. 3) It is fired only if there was ANY interaction of the user with the site. Without ANY interaction (even one click anywhere) event onbeforeunload won't be fired.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With