How to prevent closing browser window?

Another implementation is the following you can find it in this webpage: http://ujap.de/index.php/view/JavascriptCloseHook <html> <head> <script type=”text/javascript”> var hook = true; window.onbeforeunload = function() { if (hook) { return “Did you save your stuff?” } } function unhook() { hook=false; } </script> </head> <body> <!– this will ask for confirmation: –> <a href=”http://google.com”>external link</a> <!– … Read more

Crossbrowser onbeforeunload?

I found a workaround for Firefox with setTimeout function because it does not have the same behaviour as other web browsers. window.onbeforeunload = function (e) { var message = “Are you sure ?”; var firefox = /Firefox[\/\s](\d+)/.test(navigator.userAgent); if (firefox) { //Add custom dialog //Firefox does not accept window.showModalDialog(), window.alert(), window.confirm(), and window.prompt() furthermore var dialog … Read more

Prevent a webpage from navigating away using JavaScript

Using onunload allows you to display messages, but will not interrupt the navigation (because it is too late). However, using onbeforeunload will interrupt navigation: window.onbeforeunload = function() { return “”; } Note: An empty string is returned because newer browsers provide a message such as “Any unsaved changes will be lost” that cannot be overridden. … Read more

How to show the “Are you sure you want to navigate away from this page?” when changes committed?

Update (2017) Modern browsers now consider displaying a custom message to be a security hazard and it has therefore been removed from all of them. Browsers now only display generic messages. Since we no longer have to worry about setting the message, it is as simple as: // Enable navigation prompt window.onbeforeunload = function() { … Read more

How can I override the OnBeforeUnload dialog and replace it with my own?

You can’t modify the default dialogue for onbeforeunload, so your best bet may be to work with it. window.onbeforeunload = function() { return ‘You have unsaved changes!’; } Here’s a reference to this from Microsoft: When a string is assigned to the returnValue property of window.event, a dialog box appears that gives users the option … Read more