Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

CkEditor5 insertContent Function not working

I am trying to use insertContent method but getting some error.

Here is my implementation

<div id="editor">
    <p>This is the editor content.</p>
</div>
<button onclick="update()">update</button>

<script src="./node_modules/@ckeditor/ckeditor5-build-classic/build/ckeditor.js"></script>
<script>
    var editorInstance;
    ClassicEditor
        .create(document.querySelector('#editor'))
        .then(editor => {
            editorInstance = editor;
        })
        .catch(error => {
            console.error(error);
        });

    function update() {
        editorInstance.model.insertContent("<p><b>Test</b> Content</p>")
    }
</script>

update method should update the editor source with given content, but I am getting an error

Error on the console:

Uncaught TypeError: e.is is not a function at xc.Nm (converters.js:777) at xc.fire (emittermixin.js:209) at xc. [as insertContent] (observablemixin.js:259) at update (ck5.html:19) at HTMLButtonElement.onclick (ck5.html:4)

Can anyone please help in sorting out this issue?

like image 721
Nirav Goswami Avatar asked Aug 27 '26 01:08

Nirav Goswami


1 Answers

This error appears to be caused by trying to use the insertContent method to insert HTML - this method seems to expect a plain text string by default, although we can make it accept HTML with a few extra steps.

First of all, you'll need to grab the HTML Data Processor:

const htmlDP = editorInstance.data.processor;

Next you need to convert your HTML string into a viewFragment using the HTML Data Processor that we just obtained:

const viewFragment = htmlDP.toView("<p><b>Test</b> Content</p>");

Last of all, we need to convert the viewFragment to a modelFragment:

const modelFragment = editorInstance.data.toModel( viewFragment );

Now we can pass the modelFragment to the insertContent method:

editorInstance.model.insertContent(modelFragment);

This should remove the error and allow the mark-up string to be inserted into the editor

like image 109
danwellman Avatar answered Aug 31 '26 04:08

danwellman



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!