在 TinyMCE 中初始化后修改工具栏的正确方法

Proper Way Of Modifying Toolbar After Init in TinyMCE

我正在使用 javascript 扩展云托管的 LMS。因此,我们可以在页面中添加javascript,但不能修改不同组件的供应商javascript。

LMS 经常使用tinyMCE。目标是在每个 tinyMCE 编辑器的工具栏上添加一个新按钮。

问题在于,由于 tinyMCE 模块是在供应商不可修改的代码中初始化的,我们无法修改 init() 调用。因此,我们不能在 init() 对象的 "toolbar" 属性 上添加任何文本。

所以我以一种有点笨拙的方式完成了这个:

tinyMCE.on('AddEditor', function(e){
  e.editor.on('init', function(){
    tinyMCE.ui.Factory.create({
      type: 'button',
      icon: 'icon'
    }).on('click', function(){
      // button pressing logic
    })
    .renderTo($(e.editor.editorContainer).find('.mce-container-body .mce-toolbar:last .mce-btn-group > div')[0])
  });
});

所以这行得通,但不用说,我不太愿意在 DOM 中寻找这样的特定位置来插入按钮。虽然这行得通,但我不认为创作者有意这样使用它。

初始化后,如果不能修改初始化代码,有没有合适的方法将按钮添加到工具栏?

我找到了一个更优雅的解决方案,但它仍然感觉有点像 hack。这是我得到的:

// get an instance of the editor
var editor=tinymce.activeEditor; //or tinymce.editors[0], or loop, whatever

//add a button to the editor buttons
editor.addButton('mysecondbutton', {
  text: 'My second button',
  icon: false,
  onclick: function () {
    editor.insertContent('&nbsp;<b>It\'s my second button!</b>&nbsp;');
  }
});

//the button now becomes
var button=editor.buttons['mysecondbutton'];

//find the buttongroup in the toolbar found in the panel of the theme
var bg=editor.theme.panel.find('toolbar buttongroup')[0];

//without this, the buttons look weird after that
bg._lastRepaintRect=bg._layoutRect;

//append the button to the group
bg.append(button);

感觉应该还有比这更好的,但是没找到

其他说明:

  • 需要丑陋的 _lastRepaintRect 因为 repaint 方法,无论您是否添加新按钮,它都会使按钮看起来很难看 是否控制
  • 查看代码,没有办法添加新的控件到 没有重绘的工具栏,没有办法绕过它 没有丑陋的黑客
  • append(b) 等同于 add(b).renderNew()
  • 你可以使用下面的代码来添加按钮而不用破解,但是你会短路很多其他的东西:

代码:

bg.add(button);
var buttonElement=bg.items().filter(function(i) { return i.settings.text==button.text; })[0];
var bgElement=bg.getEl('body');
buttonElement.renderTo(bgElement);