Track changes to multiple Ckeditor 5 instances in Javascript

Viewed 270

I'm accessing an iframe thru fancybox 3 with multiple ckeditor. It's working well but I want to track if a user has inputted anything on the textboxes so that I can change the button of the fancybox and give them an alert once they hit close. This is my JS code on the iframe page:

  window.editors = {};

  document.querySelectorAll( '.editor' ).forEach( ( node, index ) => {
    ClassicEditor
      .create( node, {
        removePlugins: ['Heading', 'BlockQuote', 'CKFinderUploadAdapter', 'CKFinder', 'EasyImage', 'Image', 'ImageCaption', 'ImageStyle', 'ImageToolbar', 'ImageUpload', 'MediaEmbed'],
      } )
      .then( newEditor => {
        window.editors[ index ] = newEditor;
      } );

      editors[ index ].document.on( 'change', () => {
        console.log( 'Alert: The document has changed!, are you sure you want to close without saving?' );
      } );

  } );

But it's giving me an error:

ifram.php:1070 Uncaught TypeError: Cannot read properties of undefined (reading 'document')

at ifram.php:1070

at NodeList.forEach (<anonymous>)

at ifram.php:1060

I also tried taking this out off document.querySelectorAll() function

  editors.document.on( 'change', () => {
    console.log( 'Alert: The document has changed!, are you sure you want to close without saving?' );
  } );

But it gave me another error: Uncaught TypeError: Cannot read properties of undefined (reading 'on')

1 Answers

You could use newEditor.model.document.on('change:data') document

<script src="https://cdn.ckeditor.com/ckeditor5/30.0.0/classic/ckeditor.js"></script>
<textarea class="editor"></textarea>
<script>
window.editors = {};
document.querySelectorAll( '.editor' ).forEach( ( node, index ) => {
  ClassicEditor
  .create( node, {
    removePlugins: ['Heading', 'BlockQuote', 'CKFinderUploadAdapter', 'CKFinder', 'EasyImage', 'Image', 'ImageCaption', 'ImageStyle', 'ImageToolbar', 'ImageUpload', 'MediaEmbed'],
  } )
  .then( newEditor => {
    window.editors[ index ] = newEditor;
    newEditor.model.document.on('change:data', ()=> {
        console.log( 'Alert: The document has changed!, are you sure you want to close without saving?' );
    });
  } );
});
</script>

Related