How to trigger page leave warning on TinyMCE edit?

Viewed 1218

I recently upgraded to a new version on TinyMCE (4.6.1, which is no longer the newest version). There were several areas of my site that were affected that used to trigger a "Do you want to leave this site?" warning when the TinyMCE box had been edited but the form it was in wasn't submitted. Now no warning is triggered.

I have tried many solutions (autosave plugin, autosave_ask_before_unload init property, throwing change events), but the closest I've come to fixing this makes the warning trigger regardless of if the TinyMCE area has been edited or not. There is a lot of information on how to add or remove this functionality for 3.x, but less for 4.x.

I need changes to the TinyMCE field to make a warning trigger if you try to leave the page without submitting the form and no warning to trigger in any other case.

2 Answers

For more information. Best way to detect when a user leaves a web page?

window.addEventListener('beforeunload', function(e) {
  var myPageIsDirty = tinymce.activeEditor.isDirty()
  if(myPageIsDirty) {
    //following two lines will cause the browser to ask the user if they
    //want to leave. The text of this dialog is controlled by the browser.
    e.preventDefault(); //per the standard
    e.returnValue = ''; //required for Chrome
  }
  //else: user is allowed to leave without a warning dialog
});
Related