2010-06-13 59 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