Jon
Jon

Reputation: 379

CKEditor: Access insertHtml() method from external script

I am building a custom text editor using CKEditor and I want to write my own JavaScript functions to insert HTML into the CKEditor window.

CKEditor has a method called editor.insertHtml() that inserts HTML at the location of the cursor in the document. This method can be accessed from within a CKEditor plugin but I would prefer the freedom to write my own functions outside of CKEditor, then insert the resulting HTML into the editor.

So how do I access editor.insertHtml()? I have copied my code below. I tried using CKEDITOR.instances.editor1.insertHtml() but this doesn't work.

This question CKEditor editor1.insertHtml() not working for me suggests that I need to be listening for the instanceReady event, but I'm not sure how to do this so I would appreciate a more detailed explanation. Thank you!

<html>
<head>
    <meta charset="utf-8">
    <script src="ckeditor/ckeditor.js"></script>
</head>
<body>
<textarea id="editor1"></textarea>
<script type="text/javascript">
    // Replaces the <textarea id="editor1"> with a CKEditor
    // instance, using default configuration.
    CKEDITOR.replace( 'editor1',
    {
        height:"500", width:"1000"
    });
</script>
<script type="text/javascript">
    CKEDITOR.instances.editor1.insertHtml('<h1>someText</h1>');
</script>

</body>
</html>

Upvotes: 3

Views: 4155

Answers (1)

oleq
oleq

Reputation: 15895

The instanceReady event:

Fired when a CKEDITOR instance is created, fully initialized and ready for interaction.

You can use it as follows:

CKEDITOR.replace( 'editor1', {
    height: '500', 
    width: '1000',
    on: {
       instanceReady: function() {
           // this is current editor instance
           this.insertHtml( '<h1>someText</h1>' );
       }
    }
} );

To use the API of an instance, basically put your code in instanceReady callback. Otherwise, your code will be executed while the editor is not ready yet.

Upvotes: 3

Related Questions