How do I access the contents of Wordpress Classic editor in admin area with JavaScript?

I am working on a small Wordpress plugin which uses JavaScript to add html tags with a css class to the visual text view in the Wordpress editor. I use the Classic Editor.

According to Chrome Developer tools, the visual text editor consists of a few div elements, and then an iframe element with the id content_ifr which loads a second body element which then contains all html tags pertaining to the post:

body id=tinymce class=mce-content-body content post-type-post post-status-publish post-format-standard page-template-default locale-de-de mceContentBody wp-editor wp-autoresize html5-captions data-id=content dir=ltr style=overflow-y: hidden; contenteditable=truepPost content/p/body

I have already figured out that I can access this second body element with

document.getElementById(content_ifr).contentDocument.body

But this only works with manual input in the console, after everything has loaded. It doesn't work in the JavaScript file of the plugin which the plugin's php file loads via wp_enqueue_scripts. The corresponding variable always returns null.

How can I make the contents of the Classic editor accessible to the JavaScript file of my plugin?

Topic accessibility visual-editor plugin-development cms Wordpress javascript

Category Web


To get the editor content as a string in the classic editor use this:

content = tinymce.activeEditor.getContent();

Taken from https://stackoverflow.com/a/5843951/57482

Note that you should use the APIs provided rather than directly modifying the DOM if you want to modify the content. If you don't, you won't update plugins local states in javascript causing problems. Modifying the DOM should be a last resort.

Also note that this will not work for the block editor. The block editor requires a completely different approach, and you can't then edit the content and put it back without breaking the blocks or turning everything into a custom HTML block causing other issues.

About

Geeks Mental is a community that publishes articles and tutorials about Web, Android, Data Science, new techniques and Linux security.