Mozilla firefox not working with window.onbeforeunload
Here is working solution for Firefox and Chrome. I haven't yet tested in Safari and Opera.
var myEvent = window.attachEvent || window.addEventListener;
var chkevent = window.attachEvent ? 'onbeforeunload' : 'beforeunload'; /// make IE7, IE8 compitable
myEvent(chkevent, function(e) { // For >=IE7, Chrome, Firefox
var confirmationMessage = 'Are you sure to leave the page?';
(e || window.event).returnValue = confirmationMessage;
return confirmationMessage;
});
I looked for a Firefox onbeforeunload
solution over 2 days and with no luck, so I worked hard on this, and did it with a little trick.
In my trick, the user needs to click on the browser window at least once.
If the user clicks on the window and then clicks on the back button, refreshes the page, or tries to exit the page, onbeforeunload
events will fire,
$(window).on('beforeunload', function () {
return "Are you sure you want to exit this page?";
});
$(window).one('click',function(){
alert('hi');
$('.javavoid').trigger('click');
});
.hide{display:none;}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<body>
<a class="hide javavoid" href="javascript:void(0)">asdf</a>
<p>Welcome, click anywhere then click on back button or refresh page</p>
</body>
Using the code given in the MDN works for me in firefox/chrome/IE11 (haven't try other browser for now).
window.onbeforeunload = function (e) {
var e = e || window.event;
// For IE and Firefox
if (e) {
e.returnValue = 'Any string';
}
// For Safari
return 'Any string';
};
here is the doc : Mdn window.onbeforeunload doc