2010-06-13 56 views
3

我试图在由TinyMCE(tinymce.moxiecode.com)或YUI的文本编辑器(http://developer.yahoo.com/yui/editor/)生成的iFrame中插入/加载JavaScript(例如prototype/jquery),以便更好地操作其中的对象/图像/ DIV 。将Javascript注入到由TinyMCE/YUI生成的iFrame中?

由TinyMCE生成的iFrame基本上是一个文本编辑器。我希望能够包含我可以操作的div,添加监听器等,以便“富文本编辑器”变得更加丰富,而不仅仅是一个textarea。

+0

什么是iframe的src? – 2010-06-13 17:42:59

+0

src =“javascript :;” 我相信这意味着YUI用JavaScript生成iFrame? – Sahadeva 2010-06-13 18:31:32

+0

no tinymce生成iframe – Thariama 2010-07-02 13:33:58

回答

0

您可以尝试以下操作。获取编辑器实例并根据需要设置内容。

// editor_id = the id of your former textarea 
editor_instance = tinymce.EditorManager.getInstanceById('editor_id'); 
// replaces the editory content 
editor_instance.setContent('<div>your_content</div>'); 

// or use the following, adds content 
editor_instance.execCommand('mceInsertContent', false , '<div>your_content</div>'); 
3

您可以动态地将脚本标签添加到iFrame的文档中。脚本标签的内容将立即执行。

下面的代码使用TinyMCE的第4版,并已在IE7,IE8,FF和Chrome

tinymce.init({ 
    setup: function (ed) { 
     // make sure the instance of the TinyMCE editor has been fully loaded 
     ed.on('init', function (args) { 
      // find the iframe which relates to this instance of the editor 
      var iframe = $("#" + args.target.id + "_ifr"); 

      // get the head element of the iframe's document and inject the javascript 
      $(iframe[0].contentWindow.document) 
       .children('html') 
       .children('head') 
       .append('<script type="text/javascript">alert("Executing inside iFrame!");</script>'); 
     }); 

    } 

}); 
0

使用我的jQuery插件htmltiny(这依赖于另一个插件jqtiny)测试:

$.fn.jqtiny=function(){ 

     if($(this).get(0).tagName==='TEXTAREA'){ 

       return $(this).prev().find('iframe').contents(); 


      }; 
    }; 

    $.fn.htmltiny=function(html){ 

      if($(this).get(0).tagName==='TEXTAREA'){ 
       if(html){ 
        $(this).jqtiny().find('body').html(html); 
        return $(this); 
       }else{ 
        return $(this).jqtiny().find('body').html(); 
       } 



      } ; 


    }; 

如果您在触发TinyMCE后检查DOM树,您会注意到tinyMCE的iframe在目标textarea被选中之前存在于div中以触发tinyMCE。 因此选择这个textarea并使用我的插件:

//to inject Javascript 

$('textarea').jqtiny().find('head').append('<script type="text/javascript">alert("Executing inside iFrame!");</script>'); 
    //to get HTML from iframe 
    $('textarea').htmltiny() 
    //to set HTML in iframe 
    $('textarea').htmltiny("<p>My new HTML</p>") 
+1

为什么只使用'tinymce.EditorManager.getInstanceById'或者在初始化函数 – 2013-09-03 10:25:57

+0

中引用它来避免编辑器的id的知识时,只需选择所有代码即可选择TinyMCE实例。 – 2013-09-03 10:58:50