0

This is simple enough in earlier version of tinyMCE, but I can't find a way to make it work in v6x (suggested answers here only apply to earlier versions, that I can see)

Here's my button:

tinymce.PluginManager.add('newButton', (editor, url) => {
   editor.ui.registry.addButton('newButton', {
      text: 'Click me',
      enabled: true,
      onAction: () => {
         alert('You clicked me')
      }
   })
   return {
   getMetadata: () => ({
      name: 'newButton',
      url: ''
   })
}
});

tinymce.init({
   selector: "textarea",
   plugins: "newButton",
   toolbar1: "newButton"
});

This works fine - click the button and you get an alert telling you you have. What I want to do now is call this click event from code (JaveScript) - I was hoping

tinymce.activeEditor.buttons['newButton'].onclick();

would work, as it does for - say - the "code" plugin; i.e. add this plugin (and button) to the editor and calling

tinymce.activeEditor.buttons['code'].onclick();

simulates clicking the toolbar button. So... how can I "click" my own custon toolbar button?

[edit] well.. that last line did work, I swear it did. Now it doesn't. wt.. :(

PSU
  • 175
  • 1
  • 9

1 Answers1

0

This may not be the "right" way (well, I know it isn't!) but I've found a way that works :)

First, I need a way to identify/find my custom button. I figured out tinymce renders them as div elements, and using

var divs = document.querySelectorAll('button');
divs.forEach((div) => {
  console.log(div.innerHTML);
})

I am able to identify it and find the HTML used - it is not graced with an id, but we can use the innerHTML property (as identified) to get it and then simulate a click- viz:

var divs = document.querySelectorAll('button');
divs.forEach((div) => {
  // NB 'DOC' is the text property of my custom button
  if (div.innerHTML === '<span class="tox-tbtn__select-label">DOC</span>') {
     // now we can simulate a click on it:
     var evt = new MouseEvent("click", {
        view: window,
        bubbles: true,
        cancelable: true
     });
     div.dispatchEvent(evt);
     return;
  }
})

(Thanks to the second answer, by Derek, here: How to simulate a mouse click using JavaScript? for the simulate click code)

[edit] better to use a for-loop rather than forEach as there's no sensible way to break out of the latter - that "return" doesn't actually do anything.

PSU
  • 175
  • 1
  • 9