Quick tip: Adjusting and inject content into tinyMCE with WordPress

So I have a very activly maintained project that still relies on a tinyMCE here and there. And I needed to process some text and after an AJAX request inject it back into a textarea/tinyMCE field, but couldn’t get it to work. Which was a bit weird, because after calling window.tinymce.editors in de browser console it showed me all the initiated editors that were present on the page… scratches head… and yupp after a console.log(window.tinymce.editors) it only showed 3 of 8 editors in the editors array.

Aha I thought, I was running my code as usual on document.addEventListener('DOMContentLoaded', () => {}); but I needed to wait untill all the other code was ran. So instead of settings a timeout ,like a barbarian we developers are, I simply tried to run my code on window.addEventListener('load', (event) => {});

Et voilà! I just needed to wait a bit longer which gave the 3rd party code time to initialize and ran. Then afterwards I could simply do:

var editor = void 0;

if ('undefined' === typeof window.tinyMCE) {
    return false;
}

editor = window.tinymce.get(editor_id);
if (!editor) {
    return false;
}
    
editor.setContent(content);

So while these little bugs and scenarios still exists, I’m not afraid to loose my job to AI. And fortunatly AI itself will create such little bugs ;)