Display a Warning When Attempting to Navigate Away with Unsaved Changes in Django Mezzanine's TinyMCE

Django
2022-08-06 02:09 (3 years ago)
Display a Warning When Attempting to Navigate Away with Unsaved Changes in Django Mezzanine's TinyMCE

If the version of tinyMCE is 4, you can add an onChange event using the setup option in tinyMCE.init.

templates/admin/blog/blogpost/change_form.html

{% extends 'admin/change_form.html' %}
{% block content %}
{{ block.super }}

<script>
 /// Page navigation confirmation
window.addEventListener('beforeunload', (event) => {
/// window.tinyMCEContentChanged is defined in tinymce_setup.js and becomes true
/// when the content of the editor is changed.
if (tinyMCEContentChanged) {
event.returnValue = 'Are you sure you want to navigate away from this page? Unsaved changes will be lost.';
}
});
/// No navigation warning when the submit button is clicked
$('input[type="submit"]').click(function() {
tinyMCEContentChanged = false;
});
</script>
{% endblock %}

static/js/tinymce_setup.js

var language_codes = {
'ar': 'ar',
...
...
};

...
...

// Becomes True with the editor's change event.
// Warn on page navigation
let tinyMCEContentChanged = false;

jQuery(function ($) {

if (typeof tinyMCE != 'undefined') {

tinyMCE.init({
selector: "textarea.mceEditor",
height: '500px',
...
...
// Add setup
// https://www.tiny.cloud/docs-4x/configure/integration-and-setup/
setup: function (editor) {
editor.on('change', function (e) {
console.log('tinyMCEOnChange');
tinyMCEContentChanged = true;
});
}
});
}
});

Please rate this article
Currently unrated
The author runs the application development company Cyberneura.
We look forward to discussing your development needs.

Categories

Archive