javascripthtmltinymce

How to Execute JavaScript Functions from Non-Editable Elements in TinyMCE?


I have non-editable buttons inside the TinyMCE text editor. I want to insert a JavaScript function so that when these buttons are clicked, the text "Hello world" is logged to the console. Here is the relevant HTML and JavaScript setup

<textarea id="tinymce">
    <div class="myclass">
        <button onclick="myFunction()">button outside</button>
    </div>
    <div class="myclass non-editable">
        <button onclick="myFunction()">button Inside</button>
        <button onclick="myFunction()">button Inside</button>
    </div>
</textarea>
tinymce.init({
    selector: 'textarea#tinymce',
    height: 500,
    content_style: `
        body { font-family:Helvetica,Arial,sans-serif; font-size:16px }
        .myclass { border: 0.1rem solid green; border-radius: 0.8rem; padding: 0.2rem; }
        .non-editable { border-color: red; }
    `,
    noneditable_class: 'non-editable'
});

function myFunction() {
    console.log("Hello world");
}

I have tried inserting the myFunction script directly into the TinyMCE content fragment, but the buttons inside the editor still don't trigger the function. Does TinyMCE support this type of functionality?


Solution

  • For security reasons, TinyMCE will never allow JavaScript to be run from within the editor itself.

    If you want on-click behavior for certain elements in the body of the editor, you may want to look at TinyMCE's event handling:

    https://www.tiny.cloud/docs/tinymce/latest/events/#handling-editor-events

    With this approach, for example, if an end users clicks a button, you could run a check on each click to see if they clicked on a button and if so, run some function, etc.