I have a very simple html file with a javascript snippet that contains a beforeunload event listener:
<!DOCTYPE html>
<html lang="en">
<body>
hello world
</body>
<script>
window.addEventListener("beforeunload", (event) => {
alert("hello");
});
</script>
</html>
Per mozilla's beforeunload documentation, I expected to see an alert('hello') pop up when i close my tab. Instead, the tab closes without anything else happening. Does anyone know what I might be doing wrong? Thanks!
Per the mozilla documentation, for chrome you must also set the return value.
<!DOCTYPE html>
<html lang="en">
<body>
hello world
</body>
<script>
window.addEventListener("beforeunload", (event) => {
event.preventDefault()
event.returnValue = '';
alert("hello");
});
</script>
</html>
The issue you might be facing is, once opening the page, you need to click in the page to make it active, then once you click to close the tab, you should get the "Are you sure" message.
Although, even then... The alert doesn't work. This would no doubt relate to the small note at the top of the documentation saying its to prevent annoying popups.