How to display the onbeforeunload dialog box when necessary?

I have a javascript editor on my web page and I would like to ask the user if he / she wants to leave the page even if there are unsaved changes.

I know that I can add a custom message to the "onbeforeunload" dialog as follows:

window.onbeforeunload = function() { return 'You have unsaved changes!'; } 

( Source ), but I want to display the dialog only where there really are unsaved changes. How to do it?

Thanks!

+6
javascript onbeforeunload
source share
1 answer

You can do something like this:

 var unsavedChanges = false; window.onbeforeunload = function() { if (unsavedChanges) return 'You have unsaved changes!'; } function makeSomeChange() { // do some changes.... unsavedChanges = true; } 

You can change unsavedChanges in "change" event handlers.

+8
source share

All Articles