Programmatically access TinyMCE editor

61 Views Asked by At

I'm trying to access tinymce editor instance in the shopify's new blog page in order to set it's contents. the 'tinymce' variable is available globally only after I press inspect element and that somehow makes it available in the console, but before that it's undefined and throws an error when I try to access it.

Following content script is injected into all frames and only executed when I manually send an article data through sendMessage from a popup script. In that context I try to access the tinymce variable, which is only available after I do the inspect element thing - weird, but ok.

chrome.runtime.onMessage.addListener(function (message, sender, sendResponse) {
    const article = message.article as Article;

    try {
        // I expect the window.tinymce to be a TinyMCE instance
        if (window.tinymce) {
            console.log(window.tinymce) // This logs a body element inside an iframe
            
            const converter = new showdown.Converter();
            const html = converter.makeHtml(article.body);

            window.tinymce.activeEditor.setContent(blogHtml);
        } else {
            // @ts-ignore
            console.log(window.tinymce, document.tinymce)
        }
    } catch (e) {
        console.log("Couldn't fill out the blog content, reason: ", e);
    }
});

When tinymce is available to the content script, it seems to be a reference to a DOM element, a body element specifically. Which isn't the TinyMCE instance that has the API methods.

I'm really confused on why the apparently same variable holds different values. I have no trouble setting the contents from devtools console apart from the variable missing if iframe is not inspected beforehand.

0

There are 0 best solutions below