0

I am trying to get the text selected event from tinymce, the way i do is as follows

const editor = global["tinymce"].activeEditor;
editor.on("NodeChange", e => {
  const selectedText = editor.selection.getContent({ format: "text" });

});

Tinymce is already loaded by wordpress before including this code, the problem i face is the NodeChange event is not triggered on the editor instance. I dont want to create a tinymce plugin for this, is this possible without creating a plugin? The code i have pasted here actually works if i add it via the console, i am missing something when i load it normally

Naveen
  • 769
  • 1
  • 9
  • 28
  • 1
    yes it is possible and you're on the right track. see here https://stackoverflow.com/questions/49228768/call-selection-jquery-event-inside-tinymce-text-selection – GrafiCode Feb 04 '20 at 11:06
  • @GrafiCode Thanks, but the usecase of mine is different than the link you have mentioned, in my case tinymce is initalized by wordpress, i cant reinitialize it again – Naveen Feb 04 '20 at 11:09
  • 1
    I get it, in this case you should look for event binding after init: https://stackoverflow.com/questions/18514994/tinymce-how-bind-on-event-after-its-initialized – GrafiCode Feb 04 '20 at 11:12
  • and i forget to add, the code i have pasted here actually works if i add it in the console, i am missing something when i load it normally. – Naveen Feb 04 '20 at 11:16

1 Answers1

0

My guess is that you have a timing issue. The editor is not "active" until TinyMCE has fully initialized. If you try to call:

const editor = global["tinymce"].activeEditor;

...before the editor is fully initialized the editor variable is likely null.

WordPress has a variety of hooks to allow you to tweak the TinyMCE configuration and that is likely a more reliable way to do what you are trying to do. You can absolutely use the setup function in the TinyMCE configuration to add your NodeChange code.

Packaging that into a WordPress plugin would certainly make it easier to deploy/update your solution but its not a requirement.

Michael Fromin
  • 13,131
  • 2
  • 20
  • 31
  • sadly, the editor variable isnt null, i did a log on that editor, it just doesn't get the events. – Naveen Feb 05 '20 at 03:33
  • And actually i can package my code inside a wordpress plugin, i dont want to create tinymce plugin for that. – Naveen Feb 05 '20 at 04:04