I've recently encountered an odd bug (?) while trying to handle an external window opened via Javascript. The idea was to add an unload event listener to the window to register if it has been closed. Now it's also possible that the main page might get refreshed, in which case I'll retrieve the reference to the window via window.open using the same target name. That's when I had to learn that basic event listeners like load, unload and beforeunload are not firing anymore when the page had been reloaded.
I tested this code with both Firefox and Chrome:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Test</title>
</head>
<body>
<button onclick="openWindow()">Open window</button>
<span id="state"></span>
</body>
<script>
document.getElementById("state").innerHTML = "Closed";
function openWindow() {
const extWindow = window.open("about:blank", "ExtWindow", 'directories=no,titlebar=no,toolbar=no,location=no,status=no,menubar=no,scrollbars=no,width=1600,height=900');
document.getElementById("state").innerHTML = "Opened";
extWindow.addEventListener('load', () => console.log('load'));
extWindow.addEventListener('beforeunload', () => console.log('beforeunload'));
extWindow.addEventListener('unload', () => {
document.getElementById("state").innerHTML = "Closed";
console.log('unload');
});
}
</script>
</html>
To replicate this behavior, open the window via the button, then reload the page with the window still opened, click the button again to retrieve reference, then close the window. None of the events will fire if the page had been reloaded. (Unfortunately window.open doesn't seem to work within a snippet.)
I'm not exactly sure if this behavior is intentional, but if so, is there something I can do to get this working?
I know I could resort to setInterval to check the closed property of the window, but I'd like to avoid any polling and rely on event listeners instead.