Reputation: 113385
I want to handle the beforeunload
event in Firefox. It is working fine except that the user needs to manually click the page or write something into an input.
I have the following piece of code that works on Firefox, but again, only if we manually click the page.
<script>
popMessage = "Foo";
window.addEventListener("beforeunload", function (e) {
(e || window.event).returnValue = popMessage; //Gecko + IE
alert(popMessage);
return popMessage;
});
</script>
I tried to add:
document.body.click()
<input type='text' autofocus>
Both are not making any change.
I also tried to use jQuery with the hope that it will handle it correctly. Still, getting the same:
<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>
These work fine on Chrome, but not on Firefox. Is there any hope to get this working without user interaction on the page?
Upvotes: 1
Views: 368
Reputation: 254
developer.mozilla.org states that "To combat unwanted pop-ups, browsers may not display prompts created in beforeunload event handlers unless the page has been interacted with." So there is no hope.
Upvotes: 1