开发者

document.execCommand in iframe don't work

开发者 https://www.devze.com 2023-03-15 06:30 出处:网络
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 t

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;
  开发者_C百科      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); 
};


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;
0

精彩评论

暂无评论...
验证码 换一张
取 消