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 to stay on the current page and retain the string that was assigned to it. The default statement that appears in the dialog box, "Are you sure you want to navigate away from this page? ... Press OK to continue, or Cancel to stay on the current page.", cannot be removed or altered.
The problem seems to be:
- When
onbeforeunload
is called, it will take the return value of the handler aswindow.event.returnValue
. - It will then parse the return value as a string (unless it is null).
- Since
false
is parsed as a string, the dialogue box will fire, which will then pass an appropriatetrue
/false
.
The result is, there doesn't seem to be a way of assigning false
to onbeforeunload
to prevent it from the default dialogue.
Additional notes on jQuery:
- Setting the event in jQuery may be problematic, as that allows other
onbeforeunload
events to occur as well. If you wish only for your unload event to occur I'd stick to plain ol' JavaScript for it. jQuery doesn't have a shortcut for
onbeforeunload
so you'd have to use the genericbind
syntax.$(window).bind('beforeunload', function() {} );
Edit 09/04/2018: custom messages in onbeforeunload dialogs are deprecated since chrome-51 (cf: release note)
how to set my own message on beforeunload event
Modern versions of browsers removed feature of custom messages (due to security reasons, I suppose).
Chrome from v > 51, Firefox > 4
Safari from v > 9.1
You can bind some callback, yet with no change in message in prompt.
Edit: found a very good documentation with compatibility graph here
Related Topics
404 Error When Trying to Register Serviceworker
Prevent Sweetalert to Be Closed on Clicking Outside the Popup Window
Highlight Menu Item When Scrolling Down to Section
Call JavaScript Function Onchange Event of Dropdown List
How to Parse Excel (Xls) File in Javascript/Html5
Js Li Tag Onclick Not Working on Ie8
How to Merge the Property With Same Key in Two Object Array
How to Wait Until an Element Exists
Best Way to Get Objects With Highest Property Value
While Looping a Jquery Ajax Call
Ask for Geolocation Permission Again If It Was Denied
Storing Object Inside a Variable from API JavaScript
How to Convert Utf8 String to Byte Array
Webaudio - Seamlessly Playing Sequence of Audio Chunks
Verify External Script Is Loaded
How to Load Script in React Component
How to Prevent Drag on a Child, But Allow Drag on the Parent