Before user navigates the page code checks if he edited some of the form fields. If he did, I display a modal window with Yes and No buttons. If he
That's not possible.
You are limited to show a text message along with the option to continue on the page or go away.
Please, see this link for more information: https://developer.mozilla.org/en-US/docs/Web/API/WindowEventHandlers/onbeforeunload
window.onbeforeunload = funcRef
funcRefis a reference to a function or a function expression.- The function should assign a string value to the
returnValueproperty of theEventobject and return the same string.Example:
window.onbeforeunload = function(e) { return 'Dialog text here.'; };
You can, after the user decides to remain on the page, show your modal, but I think it's propose will be defeated at that time.
As stated by others, you can intercept navigation by listening to click and key events on links and forms on your page, but this will not allow you to show any dialog when the user tries to enter a URL manually, close the tab, close the window, press the reload, back or forward buttons, etc.
The beforeunload event is designed this way to protect users from malicious scripts.
If permitted that kind of control someone could lock your browser in a desired page, not allowing you to navigate away or close the window.
Edit.:
I've managed to show a confirmation dialog that works almost the same way you want by attaching to the 2 events beforeunload and unload. It works on Internet Explorer 11, Firefox 40 and Safari 5.1 for Windows (that I can confirm right now):
var alreadyTriggered = false;
function onQuit() {
if (alreadyTriggered) return true;
alreadyTriggered = true;
if (confirm('Sure?')) {
alert('OK');
} else {
alert('Cancel');
}
}
window.onbeforeunload = onQuit;
window.onunload = onQuit;
You can reload the page to test it here.
This relies on the break on the JS event loop that the confirmation dialog causes and there is no way of making this work with custom dialogs because the page will change or close before the users gets the chance to interact with it.
There is still no way to avoid the page to change or close and also no way to make this work in Chrome. This will also not work in Firefox the event was not fired by an user interaction.