Search code examples
javascriptckeditor

CKEditor5 can't get editor instance


I have this CKEditor 5 code for my website. I want to get the data and set new data but i can't get the editor instance. Here is revelant codes.

<script type="module">
import {
    // ...
} from 'ckeditor5';

import translations from 'ckeditor5/translations/tr.js';

const editorConfig = {
    // ...
};

let CKeditor;
ClassicEditor.create(document.querySelector('#editor'), editorConfig).then( editor => {
        editor.setData("<p>Hello World</p>");

        CKeditor = editor;
    } )
    .catch( error => {
        console.error( error );
    } );

console.log (CKeditor);
CKeditor.setData("<p>Another Hello World</p>");
</script>

<textarea name="content" id="editor" class="block"></textarea>

When executed, CKeditor value is undefined and the editor shows "Hello World", not "Another Hello World". I tried other aproaches like this, but it didn't work either.

const domEditableElement = document.querySelector( '.ck-editor__editable' );
    
const editorInstance = domEditableElement.ckeditorInstance;
    
editorInstance.setData( '<p>Another Hello World<p>' );

Solution

  • The ClassicEditor.create() method returns a Promise. Therefore, you should use await when calling this method if you want to use the editor instance. Or add your code in the then handler.

    async function initializeEditor() {
      const editor = await ClassicEditor.create(document.querySelector('#editor'));
    
      editor.setData(...)
    
    }