How to get syntax highlighting to work inside a text editor iframe? (JavaScript, CSS)

842 views Asked by At

I am building a text editor using an iframe as the editor.

I'm working on a menu item that when clicked, allows the user to write a block of code that is then styled using the Prism syntax highlighter, and added inside the iframe with the rest of the text content.

When building a normal webpage, any code wrapped in pre and code tags are instantly styled to look like this:

enter image description here

My problem is that I can't find a way to make the Prism syntax highlighter work inside my text editor iframe (would have the same problem with any syntax highlighter).

The prism.css file does work inside the iframe, but the prism.js file does not. I know this because when the function runs, the output has not been processed by the javascript file which adds the classes needed to change the colours using the css file:

enter image description here

This image shows what happens when you click the menu item. The html gets inserted into the iframe but without any style whatsoever. Then when you press the preview button to see what the blog post looks like, no styling has been applied to the codeblock text because prism.js was not run inside the iframe.

I have tried including the script inside the head tags of the iframe itself with a class of "allow-scripts" and "allow-cross-origin", but that didn't work.

I would really appreciate any ideas or solutions for this one.

Here is my code:

HTML:

enter image description here

JavaScript (function called when "" menu item clicked):

enter image description here

2

There are 2 answers

1
Mark On

An iframe is only a loader for an external web source - content from another website, or an entire page from an external website. For security reasons, the ability to manipulate the content inside an iframe is disabled, to prevent XSS and Phishing attacks.

An iframe is not a container for elements or content from your own webpage. Content that gets placed inside an iframe will be ignored by the browser.

<iframe>This is my content</iframe>

An iframe requires a source to load from.

<iframe src="https://www.wikipedia.com/"></iframe>

There is no reason to use an iframe as a container for your own content. If you are just using the iframe as the container for your editor, virtually any other HTML tag will work just fine. Switch the <iframe> to a <div> and you'll have a working editor.

0
AudioBubble On

Figured out where I was going wrong, the prism.js file ran when the page is loaded, and didn't run again once new content was added to the page. Solved it by adding the src link to the script tags after the code block was added to the page.