sakinobashi
sakinobashi

Reputation: 207

How to get content from a TinyMCE instance within an iframe

I have an instance of TinyMCE (v5) which is inside an iframe itself. However, I want its content to be included when I submit a form in the parent page. Since its content is not added automatically to the POST data, I'm trying to intercept the form submit, copy the content of the TinyMCE instance to a hidden field out of the iframe, and proceed with the submission.

However, I'm having trouble getting to the TinyMCE instance within the iframe.

I managed to access the contents of the iframe this way: $('#iframe').contents().find('[name="input"]')

And I know that to get a TinyMCE instance's content we should use getContent(). I can't, however, get the TinyMCE instance from outside the iframe.

I also tried initialising TinyMCE from outside the iframe (i.e., from the parent page) by using the target option instead of selector, but in that case TinyMCE wouldn't even initialise properly.

Is there any way to get the iframe's TinyMCE instance? It's important for me to keep it inside the iframe because I want the editor's CSS to be independent from the main page's.

Upvotes: 0

Views: 1540

Answers (1)

blex
blex

Reputation: 25634

When you include TinyMCE into a page, it registers the tinymce variable to the window of that page, so that you can access it and setup your editor.

When that page is inside an iframe, to access this window from the parent, you can do:

$('#iframe')[0].contentWindow;
// or `document.querySelector('#iframe).contentWindow` in plain JS

Once you know this, it's easy to access the TinyMCE editor's contents:

$("#iframe")[0].contentWindow.tinymce.editors["input-id"].getContent();

Upvotes: 2

Related Questions