John Smith
John Smith

Reputation: 111

document.execCommand in iframe don't work

I'm working on my WYSIWYG editor. And I have code like this:

doc.execCommand(cmd, false, null);

The cmd argument would be 'Bold', 'Italic', etc. And the doc variable refer to the document in the iframe, which is initialized somewhere else:

doc = iframe1.contentWindow.document; 

It works fine in Chrome, but in IE(my is IE9) doesn't work at all.

I debugged my code with the developer tool and found nothing wrong, the execCommand function just doesn't work.

I have searched through the Internet and couldn't found an available solution.

Would anyone give me a help?

Code sample:

function $see(e, o) {
    var that = this;
    ...
    this.e = $see.make('iframe', { 'class': 'editor' }); // editor iframe    
    this.e.onload = function () {  // call when the document is loaded
        var d = that.e.contentWindow || that.e.contentDocument;
        if (d.document) d = d.document;
        that.doc = d;
        that.doc.write('<html><head></head><body></body></html>');
        that.doc.body.innerHTML = that.ta.value; // that.ta refers to an textarea
        that.doc.body.setAttribute('contenteditable', 'true');
        ...
    };
}
$see.prototype.exec = function (cmd) { 
    // call in an <a> tag's onclick event outside the iframe
    this.doc.execCommand(cmd, false, null); 
};

Upvotes: 3

Views: 3335

Answers (1)

Ibu
Ibu

Reputation: 43810

That is because there are different methods to work with iframe in different browsers

here is how it should work

var doc= iframe1.contentWindow || iframe1.contentDocument;
if (doc.document)
 doc=doc.document;

UPDATE

ok i think i made a little mistake here is how it should look like:

var doc = iframe.contentWindow || iframe.contentDocument.defaultView;
if (doc.document)
doc=doc.document;

Upvotes: 3

Related Questions