4

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.

Autumn Leonard
  • 514
  • 8
  • 22

2 Answers2

4

It's recommended that you use the IsDirty TinyMCE function

This is a function that returns a true/false value if the editor is dirty or not. The editor is considered "dirty" if a user has made modifications to the contents.

Code:

if (tinyMCE.activeEditor.isDirty())
    alert("You must save your contents.");

There is an SO answer here that suggests using onchange, however there is an open bug with onchange (it doesn't always fire).

The TinyMCE docs for the onchange callback "strongly recommend" IsDirty in preference, and explain why:

We strongly recommend users to utilize the isDirty method to determine if the editor contents were changed or not since this is much more exact because it doesn't need undo levels/blurring, etc.

It is important to note that the onchange callback will not fire on each keystroke due to performance considerations. Executing the onchange callback all the time is just a bad design practice and it wastes the users CPU. It's better to check the isDirty state before leaving the page in a document onbeforeunload event. This is how the autosave plugin functions. The isDirty approach is the recommended way of tracking if an editor instance has been modified or not.

Rachel Gallen
  • 27,943
  • 21
  • 72
  • 81
2

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
});
Ego Slayer
  • 1,987
  • 2
  • 22
  • 17