Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Use jQuery in a TinyMCE plugin

I'm writing a plugin for TinyMCE and I want to use jQuery to do some manipulation on the document being editted.

I'm not looking for a way to use TinyMCE with jQuery (e.g. an .tinymce() method on a selector), I know there are solutions for that.

Basically I need to include jQuery in the iframe generated by TinyMCE.

tinymce.dom.ScriptLoader seems to load in the parent window, not in the iframe, so that's not an option.

What I've tried so far:

  • Load jquery through ScriptLoader in the parent and plugin context (the latter has no effect at all, the former loads it in the wrong context)
  • Access window.parent.$, which is undefined (even if it's loaded in the parent window)
  • RTFM'ing and googling but no relevant hits. If the plugin opens a dialog then there is an option to load additional javascript, but that's also not what I need.

Anyone using jQuery in TinyMCE plugins? How?

Update / solutution

Thanks to Thariama's suggestion I was able to get this to work. You can use either an explicit tinymce.get() to get the editor, or the 'ed' instance that's passed to your plugin's init() method. It turns out however that at the init stage itself you cannot (yet) access the parent this way. You can do this in a specific handler.

E.g.

(function($) {
  tinymce.create('tinymce.plugins.SOSamplePlugin', {
    init: function(ed, url) {
        $ = ed.getWin().parent.jQuery; // <- WON'T WORK!

        ed.addCommand('soCmd', function(ui, v) {
            if(e = ed.selection.getNode()) {
                $ = ed.getWin().parent.jQuery; // <- WORKS!
                $(e).wrap('<div class="sample" />');
                ed.execCommand("mceRepaint");
            }
        });
        ed.addButton('SO', {
           title: 'Title',
           cmd: 'soCmd',
           image: 'somebutton.png'
        });
    },
    getInfo: function() {
        return {
            longname: 'Example Plugin',
            author: 'Ivo',
            authorurl: 'http://vanderwijk.info/',
            infourl: 'http://vanderwijk.info',
            version: '1.0'
        };
    }
  });
  tinymce.PluginManager.add('so', tinymce.plugins.SOSamplePlugin);
})($);
like image 342
Ivo van der Wijk Avatar asked Nov 11 '12 16:11

Ivo van der Wijk


1 Answers

It is easy

var editor = tinymce.get('your_editor_id');

jQuery is acessible using

editor.getWin().parent.jQuery
like image 175
Thariama Avatar answered Oct 11 '22 21:10

Thariama