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

Django
2022-08-06 11:09 (2 years ago) ytyng

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;
});
}
});
}
});

Currently unrated

Comments

Archive

2024
2023
2022
2021
2020
2019
2018
2017
2016
2015
2014
2013
2012
2011