Running JavaScript in iFrame

I have an iframe inside of a widget that can have multiple “file” tabs, and the user can switch between the tabs and use the corresponding editor.

When the user is typing within an editor, the contents of that said editor will be inserted into the iframe, according to the mode they are using (html, css, javascript), using editor.getValue();

This is working, it is adding the appropriate value into the corresponding script tag. However, it is not actually “updating” or “running” the javascript, it only works on load in my function named setIframe(), using the same editor.getValue() function… So, I don’t understand why it isn’t working.

EDIT: I am now using .replaceWith() rather than inserting the new script with .html(), however, this is causing an issue with editor.getValue(). It is now getting all previous values as well as the current value of the editor.
To explain, the original value is setting the div’s background color to blue on click, great, it’s working. However, when I alter that same line, to change the color to red, when I click the div in the iframe it changes the background to blue and the color to red, even though the current value in the editor is only told to change the color, not the background…

  • Also, when removing the tab, thus removing the corresponding editor and script tag, the iframe is still receiving the functions, even though the script tag is no longer there.

  • Another note: I even attempted to remove all contents from the iframe on keyup then add them back, and the issue was still occurring, so it must have something to do with editor.getValue();

EDIT: Tried using eval to update the script, still encountering the issue. Check the second link.

Here is my codepen: https://codepen.io/Souleste/pen/WVemXN
Simplified codepen: https://codepen.io/Souleste/pen/xvjEQQ
*line 140* is where I am encountering the issue…

code is a bit messy fyi.