In my quest to handle the beforeunload
event in Firefox, I've encountered a small hurdle. It seems to be working smoothly, but only if the user physically interacts with the page by clicking on it or entering text into an input field.
Below is the code snippet that effectively triggers the event in Firefox, as long as there is manual engagement:
<script>
popMessage = "Foo";
window.addEventListener("beforeunload", function (e) {
(e || window.event).returnValue = popMessage; //Gecko + IE
alert(popMessage);
return popMessage;
});
</script>
I attempted to solve the issue by trying out the following methods:
document.body.click()
<input type='text' autofocus>
Unfortunately, both attempts proved ineffective in resolving the problem.
Even turning to jQuery didn't provide a solution, as shown in this script:
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.2.4/jquery.min.js"></script>
<script>
$(window).on('beforeunload', function(){
return 'Are you sure you want to leave?';
});
</script>
While these approaches may work seamlessly on Chrome, they fall short on Firefox. Is there any possibility of achieving the desired functionality without requiring user interaction?