开发者

Inject Javascript into iFrame generated by TinyMCE/YUI?

I开发者_StackOverflow'm trying to insert/load javascript (e.g. prototype/jquery) into the iFrame generated by TinyMCE (tinymce.moxiecode.com) or YUI's text editor (http://developer.yahoo.com/yui/editor/) so as to better manipulate the objects/images/DIVs inside it.

The iFrame generated by TinyMCE is basically a text editor. I want to be able to include divs that I can manipulate, add listeners to, etc, so that the "rich text editor" becomes richer, and not just a textarea.


You can dynamically add a script tag to the document of the iFrame. The contents of the script tag will be immediately executed.

The following code uses TinyMCE version 4 and has been tested on IE7, IE8, FF and 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>');
        });

    }

});


You may try the following. Get the editor instance and set the content as you wish.

// 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>');


Use my jquery plugin htmltiny (which depends on another plugin 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();
                }



           }  ;


    };

if you inspect DOM tree after trigging TinyMCE , you will note that iframe of tinyMCE exists in div before the target textarea wich is selected to trigger tinyMCE. So select this textarea and use my plugin :

//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>")
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜