Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Detect when text has changed AND editor has lost focus in CKEditor 5

I'm trying to implement an autosave feature in CKEditor 5, where a save only occurs if changes were made and after the editor has lost focus.

How could I do this? The documentation has been very confusing to me.

This is the closest I've gotten:

function onChange(el,editor) {
    editor.document.once('change',function(evt,data) {
        $(el).one('blur',function() {
            saveFunction();
            onChange(el,editor);
        });
    });
}

onChange(el,editor);

The problem with my solution is the blur event fires whenever CKEditor brings up a modal.

like image 760
Adam Cook Avatar asked Sep 11 '25 21:09

Adam Cook


1 Answers

To track the focused element of the editor ui you can use the focusTracker (available on editor.ui.focusTracker). It tracks various parts of the editor that are currently focused.

The focusTracker.isFocused is true whenever any of the editor's registered components are focused. For the classic editor build the focused elements might be one of:

  • editing area,
  • toolbar,
  • contextual toolbar.
editor.ui.focusTracker.on( 'change:isFocused', ( evt, name, isFocused ) => {
    if ( !isFocused ) {
        // Do whatever you want with current editor data:
        console.log( editor.getData() );
    }
} );
like image 152
jodator Avatar answered Sep 13 '25 11:09

jodator