1

It appears that with the latest release of Chrome (Version 73.0.3683.103 (Official Build) (64-bit)), window onunload event handler isn't being called.

In the latest version of Chrome, my onunload anonymous function seems unreachable.

I'm following MDN Web Docs (https://developer.mozilla.org/en-US/docs/Web/API/WindowEventHandlers/onunload).

window.addEventListener('unload', function (e) {
  console.log('It worked');
  debugger;
});

When I run developer tools in each browser, my snippet of code in Chrome Version 66.0.3359.117, and in Firefox 66.x pauses on the debugger breakpoint as expected when refreshing the window or clicking the back/forward button. Exiting out of the tab, or completely closing the browser works as expected.

https://codepen.io/anon/pen/jRxJxJ

Kyle Dalan
  • 15
  • 1
  • 4
  • It may have to do with the iframe. Putting that code into a *top-level* ` – CertainPerformance Apr 20 '19 at 00:04
  • it does the `console.log` but doesn't stop at `debugger` - I'm actually surprised any browser would stop at `debugger` on unload!! – Jaromanda X Apr 20 '19 at 01:25
  • 1
    @CertainPerformance, after I put the code in the top level, or just directly into the console, it works when I close the browser tab. The back, forward, and refresh buttons still don't seem to be reaching the unload hook for me. – Kyle Dalan Apr 22 '19 at 16:58

1 Answers1

2

Instead unload, use window.onbeforeunload for Chrome and it will work fine!

window.onbeforeunload = function (e) {
  console.log('It worked');
  debugger;
};

Here is the event triggered in Chrome when I close the window. enter image description here

Jonathan Gagne
  • 4,241
  • 5
  • 18
  • 30