Ken Haynes Ken Haynes - 1 month ago 7x
Javascript Question

Listener Events being reset on setData and mode change, using CKEditor

Whenever my script calls setData or changes the mode ("source", "WYSIWYG"), the Listeners for the Events I have assigned, are no longer called.

Research has taught me why and I have been experimenting with suggested solutions (CKEDITOR.setData prevents attaching of events with .on function), including those from the official documentation (!/api/CKEDITOR.editor-event-contentDom), but none of the resolutions work for me as documented, and I have no idea why.

Has anyone else here managed to resolve this issue? If so, I would be most grateful to find out how.

We are current running version 4.5.10 of CKEditor.

Thanking you in anticipation.


// Works until setData() is called or until the view mode is changed ("WYSIWYG", "SOURCE).

ev.editor.document.on( 'keydown', function( evt )
console.log("Key Down");

// This appears to be the recommended resolution however, this does not
// work for me even prior to setData() being called of the view mode being changed.

editor.on( 'contentDom', function() {
var editable = editor.editable();

editable.attachListener( editor.document, 'keydown', function() {
console.log("Key Down"); // Never executed
} );
} );

UPDATE: This solution (suggested by Dekel) looks to me as it should work. However, I suspect that I have not implemented it correctly so the Key Down event is not firing. Any thoughts on this:

for (var i in CKEDITOR.instances) {
CKEDITOR.instances[i].on('contentDom', function() {
CKEDITOR.instances[i].document.on('keydown', function(event) {
console.log('key down')


Took some time to understand what the problem is, but I think this is the solution that you are looking for.

You need to attach the keydown event everytime the DOM is ready. To do so - you need to listen to the contentDom event of the editor, and then to register the keydown event on the editor's document.

CKEDITOR.instances.editor1.on( 'contentDom', function() {
    CKEDITOR.instances.editor1.document.on('keydown', function(event) {
        console.log('key down')

In this example - editor1 is the name of the ckeditor instance.

You can check this working example:

In case you have multiple instances you will need to loop over them and add it to each of them:

for (var x in CKEDITOR.instances) {
    CKEDITOR.instances[x].on('contentDom', ...