Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

CKEditor - destroy an instance when the DOM node has been deleted

Reading through the CKEditor documentation, I see that they have an option to destroy an instance with CKEDITOR.instances.instanceName.destroy();. However, if the DOM has changed, and the whole WYSIWYG DOM structure has been removed, I get the following error in Chrome:

Uncaught TypeError: Cannot read property 'document' of null

...and the following one in Firefox:

i.contentWindow is null

Is there any way to work around this?

Due to the way my app is structured (loading content via AJAX), I cannot call .destroy() when the elements are still on the page.

like image 244
Joseph Silber Avatar asked Nov 01 '11 02:11

Joseph Silber


3 Answers

If you need to destroy the ckeditor object and the elemnets in the DOM AFTER an AJAX call, you can do it by setting a boolean parameter to the function call destroy(true). This way it wont try to update the DOM:

var editor = CKEDITOR.instances[name];
if (editor) { editor.destroy(true); }
CKEDITOR.replace(name);

I have wrote 2 functions to be able to control these things a bit better. Notice that I have declared a variable before these functions can be used, but there are much slicker ways, but this approach was good enough for the purpose I needed it(I use and need only one instance):

    if(typeof(editor) == 'undefined')
        var editor=null;

    function ck_delete(editor)
    {
        if(typeof(editor) != 'undefined' && editor!=null)
            editor.destroy();
    }

    function ck_init(ck_inst_name)
    {
        var el_id=document.getElementById(ck_inst_name);
        if(typeof(el_id) != 'undefined' && el_id!=null)
        {
            if(typeof(editor) == 'undefined' || editor==null)
            {
                editor=CKEDITOR.replace( ck_inst_name );
            }
            else
            {
                ck_delete(editor);
                editor=null;
                editor = CKEDITOR.replace( ck_inst_name );
            }
        }
    }

I also check if a HTML element that should be replaced exists so I dont get an error message.

like image 169
Erik Čerpnjak Avatar answered Oct 16 '22 17:10

Erik Čerpnjak


You can apply one of the patches at http://dev.ckeditor.com/ticket/8226 and it will work. I suggest this one: http://dev.ckeditor.com/attachment/ticket/8226/8226_5.patch

like image 43
AlfonsoML Avatar answered Oct 16 '22 19:10

AlfonsoML


We had this problem integrating CKEDITOR in GWT, in a popup dialog. When the dialog was destroyed, CKEDITOR raised this error - "Cannot read property 'document' of null." The solution was to destroy CKEDITOR before closing the dialog. (We had to extend the GWT ckeditor class in order to override this - using the editor.destroy(true) syntax given by Erik - Thanks, Erik!)

like image 1
eon Avatar answered Oct 16 '22 18:10

eon