Blog
August 4, 2014 Marie H.

Writing a TinyMCE Plugin

Writing a TinyMCE Plugin

Photo by <a href="https://www.pexels.com/@cottonbro" target="_blank" rel="noopener">cottonbro studio</a> on <a href="https://www.pexels.com" target="_blank" rel="noopener">Pexels</a>

I had to write a plugin for TinyMCE that let users see a list of predefined HTML and CSS tags for a specific platform. The documentation for writing TinyMCE plugins is sparse so I defaulted to the most practical approach: open a new window that loads an additional file.

TinyMCE 4 (original)

Register the plugin with tinymce.PluginManager.add and use editor.addButton to add a toolbar button:

// cheatsheet/plugin.js
tinymce.PluginManager.add('cheatsheet', function(editor, url) {
    editor.addButton('cheatsheet', {
        text: 'Cheatsheet',
        icon: false,
        onclick: function() {
            editor.windowManager.open({
                title: 'Cheatsheet for KB Editor',
                width: 600,
                height: 500,
                url: 'cheatsheet.php',
            });
        }
    });
});

Then wire it into TinyMCE initialization. Note that the plugin name is the first argument passed to tinymce.PluginManager.add:

tinymce.init({
    selector: 'textarea',
    plugins: [
        'advlist autolink link image lists preview anchor',
        'searchreplace wordcount fullscreen',
        'save table contextmenu paste textcolor',
        'cheatsheet',  // our custom plugin
    ],
    toolbar: 'undo redo | bold italic | cheatsheet',
    external_plugins: {
        'cheatsheet': '/plugins/cheatsheet/plugin.js',
    },
});

TinyMCE 6/7 (current API)

TinyMCE 6 dropped addButton in favour of ui.registry.addButton, and windowManager.open with a url parameter now requires the Premium tinymce.windowManager or you use an inline dialog. The simplest equivalent that works without Premium:

// cheatsheet/plugin.js
tinymce.PluginManager.add('cheatsheet', function(editor) {
    editor.ui.registry.addButton('cheatsheet', {
        text: 'Cheatsheet',
        onAction: function() {
            editor.windowManager.openUrl({
                title: 'Cheatsheet for KB Editor',
                url: '/cheatsheet.html',
                width: 600,
                height: 500,
            });
        }
    });

    return {
        getMetadata: function() {
            return { name: 'Cheatsheet Plugin', url: 'https://example.com' };
        }
    };
});

TinyMCE initialization for 6/7:

tinymce.init({
    selector: 'textarea',
    plugins: 'cheatsheet',
    toolbar: 'undo redo | bold italic | cheatsheet',
    external_plugins: {
        'cheatsheet': '/plugins/cheatsheet/plugin.js',
    },
});

The external_plugins path tells TinyMCE where to load your plugin from. Keep the plugin file at that path relative to your document root and it will be picked up automatically on init.

Tell your friends...