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 = … Read more

$(window).unload is not firing

Actually some browsers such as Google Chrome might block if you attempt to alert in a window unload. As a user I like this feature. Alerting every time you try to navigate away from a page sucks: Replace the alert with a console.log or something else less intrusive to the user and the event will … Read more

jQuery UI Dialog OnBeforeUnload

The correct way to display the alert is to simply return a string. Don’t call the alert() method yourself. <script type=”text/javascript”> $(window).on(‘beforeunload’, function() { if (iWantTo) { return ‘you are an idiot!’; } }); </script> See also: https://developer.mozilla.org/en-US/docs/Web/Events/beforeunload

Way to know if user clicked Cancel on a Javascript onbeforeunload Dialog?

You can do it like this: $(function() { $(window).bind(‘beforeunload’, function() { setTimeout(function() { setTimeout(function() { $(document.body).css(‘background-color’, ‘red’); }, 1000); },1); return ‘are you sure’; }); }); The code within the first setTimeout method has a delay of 1ms. This is just to add the function into the UI queue. Since setTimeout runs asynchronously the Javascript … Read more

window.onbeforeunload not working on the iPad?

This bit of JavaScript works for me on Safari and Chrome on ipad and iphone, as well as desktop/laptop/other browsers: var isOnIOS = navigator.userAgent.match(/iPad/i)|| navigator.userAgent.match(/iPhone/i); var eventName = isOnIOS ? “pagehide” : “beforeunload”; window.addEventListener(eventName, function (event) { window.event.cancelBubble = true; // Don’t know if this works on iOS but it might! … } );