TinyMce 5 自定义插件开发

2023-09-24 12:21 阅读

TinyMce可以通过自定义插件轻松的扩展。

注册插件

PluginManager.add(pluginId, callback)传入插件ID和插件回调方法。并建议通过getMegadata返回name(插件名称)和url(插件帮助文档的URL地址)。

tinymce.PluginManager.add('pluginId', function(editor, url) {
  // add plugin code here

  return {
    getMetadata: function () {
      return {
        name: 'Custom plugin',
        url: 'https://example.com/docs/customplugin'
      };
    }
  }
});

加载插件

可以使用两种方式加载插件。

通过URL加载

使用external_plugins配置,指定插件的URL地址。

tinymce.init({
  external_plugins: {
    pluginId: 'https://example.com/customplugincode.min.js'
  },
  plugins: ''
});

通过plugins目录

将代码拷贝到TinyMCE程序的plugins目录。然后在plugins参数里增加配置。

tinymce.init({
  plugins: 'pluginId'
});

完整示例

/*
  Note: We have included the plugin in the same JavaScript file as the TinyMCE
  instance for display purposes only. Tiny recommends not maintaining the plugin
  with the TinyMCE instance and using the `external_plugins` option.
*/
tinymce.PluginManager.add('example', function(editor, url) {
  var openDialog = function () {
    return editor.windowManager.open({
      title: 'Example plugin',
      body: {
        type: 'panel',
        items: [
          {
            type: 'input',
            name: 'title',
            label: 'Title'
          }
        ]
      },
      buttons: [
        {
          type: 'cancel',
          text: 'Close'
        },
        {
          type: 'submit',
          text: 'Save',
          primary: true
        }
      ],
      onSubmit: function (api) {
        var data = api.getData();
        /* Insert content when the window form is submitted */
        editor.insertContent('Title: ' + data.title);
        api.close();
      }
    });
  };
  /* Add a button that opens a window */
  editor.ui.registry.addButton('example', {
    text: 'My button',
    onAction: function () {
      /* Open window */
      openDialog();
    }
  });
  /* Adds a menu item, which can then be included in any menu via the menu/menubar configuration */
  editor.ui.registry.addMenuItem('example', {
    text: 'Example plugin',
    onAction: function() {
      /* Open window */
      openDialog();
    }
  });
  /* Return the metadata for the help plugin */
  return {
    getMetadata: function () {
      return  {
        name: 'Example plugin',
        url: 'http://exampleplugindocsurl.com'
      };
    }
  };
});

/*
  The following is an example of how to use the new plugin and the new
  toolbar button.
*/
tinymce.init({
  selector: 'textarea#custom-plugin',
  plugins: 'example help',
  toolbar: 'example | help'
});

参考

QQ咨询
电话
微信
微信扫码咨询