I'm making a code editor app that lets you execute HTML/CSS/JS code, but JavaScript only executes onceWhy does JavaScript only work after opening developer tools in IE once?Toggle the css property of a div using jquery/javascriptjQuery.html() - The JavaScript code is executed but disappearsEnlarge iframe without reloading html contents using only cssHow do I execute javascript only relative to that frame and not the whole window?Dynamically Add Code to IFrame without Reloading HTML or JavascriptLive editor that allows for editing of an iframe's HTML and CSS within a textarea (or similar.)HTML/TS: textarea textContent disappears after creating another textarea or after button clickScripts executed only once, with async bootstrap modalAssigning window.parent.location.href = window.location.href

How can I effectively communicate to recruiters that a phone call is not possible?

Short story about Nobel Prize winning scientists that drop out when they realise they were incorrect

Single word for "refusing to move to next activity unless present one is completed."

How effective would wooden scale armor be in a medieval setting?

Why weren't bootable game disks ever common on the IBM PC?

Why are Democratic presidential candidates promising free health care for Illegal Immigrants?

Employers keep telling me my college isn't good enough - is there any way to fix this?

Does changing permissions to a certain role affects other role?

Is it OK to leave real names & info visible in business card portfolio?

Does throwing a penny at a train stop the train?

Would it be appropriate to sand a floor between coats of poly with a handheld orbital sander?

Is "De qui parles-tu" (for example) as formal as it is in English, or is it normal for the French to casually say that

A horrible Stockfish chess engine evaluation

Word meaning to destroy books

What is /bin/red

What's the point of having a RAID 1 configuration over incremental backups to a secondary drive?

When an electron changes its spin, or any other intrinsic property, is it still the same electron?

What happens to unproductive professors?

Why did Harry Potter get a bedroom?

What are the original Russian words for a prostitute?

Why return a static pointer instead of an out parameter?

Is there a strong legal guarantee that the U.S. can give to another country that it won't attack them?

Salt, pepper, herbs and spices

How can characters/players identify that a polymorphed dragon is a dragon?



I'm making a code editor app that lets you execute HTML/CSS/JS code, but JavaScript only executes once


Why does JavaScript only work after opening developer tools in IE once?Toggle the css property of a div using jquery/javascriptjQuery.html() - The JavaScript code is executed but disappearsEnlarge iframe without reloading html contents using only cssHow do I execute javascript only relative to that frame and not the whole window?Dynamically Add Code to IFrame without Reloading HTML or JavascriptLive editor that allows for editing of an iframe's HTML and CSS within a textarea (or similar.)HTML/TS: textarea textContent disappears after creating another textarea or after button clickScripts executed only once, with async bootstrap modalAssigning window.parent.location.href = window.location.href






.everyoneloves__top-leaderboard:empty,.everyoneloves__mid-leaderboard:empty,.everyoneloves__bot-mid-leaderboard:empty margin-bottom:0;








2















There are 3 textareas for for each HTML, CSS, and JS.
Typing inside the CSS & HTML textarea for example:
html background: green;
will make the iframe green, you can then change green to blue without refreshing the page and the iframe turns blue. But when I write JS code it executes only once, for example document.write("1"); prints 1 inside the iframe but if I add another document.write("2"); it leaves the iframe blank.



 // Executing code when clicking RUN

$("#runButton").click(function() // Adds the CSS code // Adds the HTML code
$("iframe").contents().find("html").html('<style>' + $("#cssCode").val() + '</style>' + $("#htmlCode").val());
/* ~~~~~~~~~~~~~~~ Placing the code from the containers into the iframe (BROWSER container) ~~~~~~~~~~~~~~~ */


// Evaluating JavaScript
document.getElementById("browserFrame").contentWindow.eval($("#jsCode").val());


);


I expect new output inside the iframe to appear each time I add JS code just as it does with HTML & CSS. Please try it out here: https://online-code-editor.netlify.com/
(don't mind the disappearing icons)



Update:

I found that this document.getElementById("browserFrame").contentDocument.location.reload(true);
reloads my iframe, but too quickly, Is there any way to make it work only when RUN is clicked?
Or perhaps add a certain delay










share|improve this question



















  • 5





    If you call document.write() after the document has been closed, the document is cleared completely. That's just the way that API works.

    – Pointy
    Mar 25 at 22:19












  • What @Pointy said, you can witness this by inspecting it in web tools, the document is completely cleared and absent once you click run a consecutive time.

    – chennighan
    Mar 25 at 22:26











  • How do sites like codepen make it work?

    – Makeyka
    Mar 25 at 22:28











  • They do things differently? Probably reload an <iframe> completely on every change.

    – Pointy
    Mar 25 at 22:30






  • 1





    Code Editors don't simply inject changes into a document, they inject the markup each time there's a change or it's run. A.e. It doesn't simply try to inject div width: 100px into <style></style> within the iframe, it injects <style> div width: 100px </style> - they rebuild the markup structure with the code instead of assuming the markup will be available to be appended to within the iframe document.

    – zfrisch
    Mar 25 at 22:34


















2















There are 3 textareas for for each HTML, CSS, and JS.
Typing inside the CSS & HTML textarea for example:
html background: green;
will make the iframe green, you can then change green to blue without refreshing the page and the iframe turns blue. But when I write JS code it executes only once, for example document.write("1"); prints 1 inside the iframe but if I add another document.write("2"); it leaves the iframe blank.



 // Executing code when clicking RUN

$("#runButton").click(function() // Adds the CSS code // Adds the HTML code
$("iframe").contents().find("html").html('<style>' + $("#cssCode").val() + '</style>' + $("#htmlCode").val());
/* ~~~~~~~~~~~~~~~ Placing the code from the containers into the iframe (BROWSER container) ~~~~~~~~~~~~~~~ */


// Evaluating JavaScript
document.getElementById("browserFrame").contentWindow.eval($("#jsCode").val());


);


I expect new output inside the iframe to appear each time I add JS code just as it does with HTML & CSS. Please try it out here: https://online-code-editor.netlify.com/
(don't mind the disappearing icons)



Update:

I found that this document.getElementById("browserFrame").contentDocument.location.reload(true);
reloads my iframe, but too quickly, Is there any way to make it work only when RUN is clicked?
Or perhaps add a certain delay










share|improve this question



















  • 5





    If you call document.write() after the document has been closed, the document is cleared completely. That's just the way that API works.

    – Pointy
    Mar 25 at 22:19












  • What @Pointy said, you can witness this by inspecting it in web tools, the document is completely cleared and absent once you click run a consecutive time.

    – chennighan
    Mar 25 at 22:26











  • How do sites like codepen make it work?

    – Makeyka
    Mar 25 at 22:28











  • They do things differently? Probably reload an <iframe> completely on every change.

    – Pointy
    Mar 25 at 22:30






  • 1





    Code Editors don't simply inject changes into a document, they inject the markup each time there's a change or it's run. A.e. It doesn't simply try to inject div width: 100px into <style></style> within the iframe, it injects <style> div width: 100px </style> - they rebuild the markup structure with the code instead of assuming the markup will be available to be appended to within the iframe document.

    – zfrisch
    Mar 25 at 22:34














2












2








2


2






There are 3 textareas for for each HTML, CSS, and JS.
Typing inside the CSS & HTML textarea for example:
html background: green;
will make the iframe green, you can then change green to blue without refreshing the page and the iframe turns blue. But when I write JS code it executes only once, for example document.write("1"); prints 1 inside the iframe but if I add another document.write("2"); it leaves the iframe blank.



 // Executing code when clicking RUN

$("#runButton").click(function() // Adds the CSS code // Adds the HTML code
$("iframe").contents().find("html").html('<style>' + $("#cssCode").val() + '</style>' + $("#htmlCode").val());
/* ~~~~~~~~~~~~~~~ Placing the code from the containers into the iframe (BROWSER container) ~~~~~~~~~~~~~~~ */


// Evaluating JavaScript
document.getElementById("browserFrame").contentWindow.eval($("#jsCode").val());


);


I expect new output inside the iframe to appear each time I add JS code just as it does with HTML & CSS. Please try it out here: https://online-code-editor.netlify.com/
(don't mind the disappearing icons)



Update:

I found that this document.getElementById("browserFrame").contentDocument.location.reload(true);
reloads my iframe, but too quickly, Is there any way to make it work only when RUN is clicked?
Or perhaps add a certain delay










share|improve this question
















There are 3 textareas for for each HTML, CSS, and JS.
Typing inside the CSS & HTML textarea for example:
html background: green;
will make the iframe green, you can then change green to blue without refreshing the page and the iframe turns blue. But when I write JS code it executes only once, for example document.write("1"); prints 1 inside the iframe but if I add another document.write("2"); it leaves the iframe blank.



 // Executing code when clicking RUN

$("#runButton").click(function() // Adds the CSS code // Adds the HTML code
$("iframe").contents().find("html").html('<style>' + $("#cssCode").val() + '</style>' + $("#htmlCode").val());
/* ~~~~~~~~~~~~~~~ Placing the code from the containers into the iframe (BROWSER container) ~~~~~~~~~~~~~~~ */


// Evaluating JavaScript
document.getElementById("browserFrame").contentWindow.eval($("#jsCode").val());


);


I expect new output inside the iframe to appear each time I add JS code just as it does with HTML & CSS. Please try it out here: https://online-code-editor.netlify.com/
(don't mind the disappearing icons)



Update:

I found that this document.getElementById("browserFrame").contentDocument.location.reload(true);
reloads my iframe, but too quickly, Is there any way to make it work only when RUN is clicked?
Or perhaps add a certain delay







javascript jquery






share|improve this question















share|improve this question













share|improve this question




share|improve this question








edited Mar 25 at 23:12







Makeyka

















asked Mar 25 at 22:17









MakeykaMakeyka

155 bronze badges




155 bronze badges







  • 5





    If you call document.write() after the document has been closed, the document is cleared completely. That's just the way that API works.

    – Pointy
    Mar 25 at 22:19












  • What @Pointy said, you can witness this by inspecting it in web tools, the document is completely cleared and absent once you click run a consecutive time.

    – chennighan
    Mar 25 at 22:26











  • How do sites like codepen make it work?

    – Makeyka
    Mar 25 at 22:28











  • They do things differently? Probably reload an <iframe> completely on every change.

    – Pointy
    Mar 25 at 22:30






  • 1





    Code Editors don't simply inject changes into a document, they inject the markup each time there's a change or it's run. A.e. It doesn't simply try to inject div width: 100px into <style></style> within the iframe, it injects <style> div width: 100px </style> - they rebuild the markup structure with the code instead of assuming the markup will be available to be appended to within the iframe document.

    – zfrisch
    Mar 25 at 22:34













  • 5





    If you call document.write() after the document has been closed, the document is cleared completely. That's just the way that API works.

    – Pointy
    Mar 25 at 22:19












  • What @Pointy said, you can witness this by inspecting it in web tools, the document is completely cleared and absent once you click run a consecutive time.

    – chennighan
    Mar 25 at 22:26











  • How do sites like codepen make it work?

    – Makeyka
    Mar 25 at 22:28











  • They do things differently? Probably reload an <iframe> completely on every change.

    – Pointy
    Mar 25 at 22:30






  • 1





    Code Editors don't simply inject changes into a document, they inject the markup each time there's a change or it's run. A.e. It doesn't simply try to inject div width: 100px into <style></style> within the iframe, it injects <style> div width: 100px </style> - they rebuild the markup structure with the code instead of assuming the markup will be available to be appended to within the iframe document.

    – zfrisch
    Mar 25 at 22:34








5




5





If you call document.write() after the document has been closed, the document is cleared completely. That's just the way that API works.

– Pointy
Mar 25 at 22:19






If you call document.write() after the document has been closed, the document is cleared completely. That's just the way that API works.

– Pointy
Mar 25 at 22:19














What @Pointy said, you can witness this by inspecting it in web tools, the document is completely cleared and absent once you click run a consecutive time.

– chennighan
Mar 25 at 22:26





What @Pointy said, you can witness this by inspecting it in web tools, the document is completely cleared and absent once you click run a consecutive time.

– chennighan
Mar 25 at 22:26













How do sites like codepen make it work?

– Makeyka
Mar 25 at 22:28





How do sites like codepen make it work?

– Makeyka
Mar 25 at 22:28













They do things differently? Probably reload an <iframe> completely on every change.

– Pointy
Mar 25 at 22:30





They do things differently? Probably reload an <iframe> completely on every change.

– Pointy
Mar 25 at 22:30




1




1





Code Editors don't simply inject changes into a document, they inject the markup each time there's a change or it's run. A.e. It doesn't simply try to inject div width: 100px into <style></style> within the iframe, it injects <style> div width: 100px </style> - they rebuild the markup structure with the code instead of assuming the markup will be available to be appended to within the iframe document.

– zfrisch
Mar 25 at 22:34






Code Editors don't simply inject changes into a document, they inject the markup each time there's a change or it's run. A.e. It doesn't simply try to inject div width: 100px into <style></style> within the iframe, it injects <style> div width: 100px </style> - they rebuild the markup structure with the code instead of assuming the markup will be available to be appended to within the iframe document.

– zfrisch
Mar 25 at 22:34













1 Answer
1






active

oldest

votes


















1














Instead of reloading the iframe - use postMessage.

Here's an example - having a parent page with HTML, CSS, JS textareas, and a sandboxed iframe for preview purpose:



enter image description here




index.html




<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>App</title>
<style>*margin:0;box-sizing:border-box; iframe,textareawidth:100%;min-height:3em;</style>
</head>
<body>

<textarea id="html">Hello, stack &lt;b&gt;overflow!&lt;/b&gt;</textarea>
<textarea id="css">body background: #F48024;</textarea>
<textarea id="js">document.body.innerHTML = "&lt;b&gt;World!&lt;/b&gt;";</textarea><br>
<iframe id="iframe" src="iframe.html" sandbox="allow-same-origin allow-scripts allow-modals allow-forms" frameborder="0"></iframe>

<script>
const textareas = document.querySelectorAll("#css, #html, #js");
const iframe = document.querySelector("#iframe");
const post = () => textareas.forEach(el => iframe.contentWindow.postMessage(
id: el.id,
value: el.value
, '*')); // Use 'http://example.com' instead of '*'

// Setup Events and Iframe Init
textareas.forEach(el => el.addEventListener('input', post));
iframe.addEventListener('load', post);
</script>
</body>
</html>



iframe.html




<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Iframe</title>

<style id="__app__css"></style>
<script id="__app__js"></script>
<script>
window.addEventListener('message', (evt) =>
// if (evt.origin !== "http://example.com") return; // Fix and uncomment in production
document.getElementById(`__app__$evt.data.id`).innerHTML = evt.data.value;
if (evt.data.id==='js') eval(evt.data.value);
);
</script>
</head>

<body id="__app__html"></body>

</html>


The above is just a demo to get you started, and evals as-you-type which might be dangerous while typing for loops or annoying trying to type alert("something") - You could improve the above by adding a checkbox "Autorun" and a button "Run" that becomes unhidden if autorun is unchecked.

Also make sure to use postMessage origin in production.



https://developer.mozilla.org/en-US/docs/Web/API/Window/postMessage
https://www.html5rocks.com/en/tutorials/security/sandboxed-iframes/






share|improve this answer




















  • 1





    Thank you so much it helped me a lot

    – Makeyka
    Mar 27 at 15:01










Your Answer






StackExchange.ifUsing("editor", function ()
StackExchange.using("externalEditor", function ()
StackExchange.using("snippets", function ()
StackExchange.snippets.init();
);
);
, "code-snippets");

StackExchange.ready(function()
var channelOptions =
tags: "".split(" "),
id: "1"
;
initTagRenderer("".split(" "), "".split(" "), channelOptions);

StackExchange.using("externalEditor", function()
// Have to fire editor after snippets, if snippets enabled
if (StackExchange.settings.snippets.snippetsEnabled)
StackExchange.using("snippets", function()
createEditor();
);

else
createEditor();

);

function createEditor()
StackExchange.prepareEditor(
heartbeatType: 'answer',
autoActivateHeartbeat: false,
convertImagesToLinks: true,
noModals: true,
showLowRepImageUploadWarning: true,
reputationToPostImages: 10,
bindNavPrevention: true,
postfix: "",
imageUploader:
brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
allowUrls: true
,
onDemand: true,
discardSelector: ".discard-answer"
,immediatelyShowMarkdownHelp:true
);



);













draft saved

draft discarded


















StackExchange.ready(
function ()
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f55347213%2fim-making-a-code-editor-app-that-lets-you-execute-html-css-js-code-but-javascr%23new-answer', 'question_page');

);

Post as a guest















Required, but never shown

























1 Answer
1






active

oldest

votes








1 Answer
1






active

oldest

votes









active

oldest

votes






active

oldest

votes









1














Instead of reloading the iframe - use postMessage.

Here's an example - having a parent page with HTML, CSS, JS textareas, and a sandboxed iframe for preview purpose:



enter image description here




index.html




<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>App</title>
<style>*margin:0;box-sizing:border-box; iframe,textareawidth:100%;min-height:3em;</style>
</head>
<body>

<textarea id="html">Hello, stack &lt;b&gt;overflow!&lt;/b&gt;</textarea>
<textarea id="css">body background: #F48024;</textarea>
<textarea id="js">document.body.innerHTML = "&lt;b&gt;World!&lt;/b&gt;";</textarea><br>
<iframe id="iframe" src="iframe.html" sandbox="allow-same-origin allow-scripts allow-modals allow-forms" frameborder="0"></iframe>

<script>
const textareas = document.querySelectorAll("#css, #html, #js");
const iframe = document.querySelector("#iframe");
const post = () => textareas.forEach(el => iframe.contentWindow.postMessage(
id: el.id,
value: el.value
, '*')); // Use 'http://example.com' instead of '*'

// Setup Events and Iframe Init
textareas.forEach(el => el.addEventListener('input', post));
iframe.addEventListener('load', post);
</script>
</body>
</html>



iframe.html




<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Iframe</title>

<style id="__app__css"></style>
<script id="__app__js"></script>
<script>
window.addEventListener('message', (evt) =>
// if (evt.origin !== "http://example.com") return; // Fix and uncomment in production
document.getElementById(`__app__$evt.data.id`).innerHTML = evt.data.value;
if (evt.data.id==='js') eval(evt.data.value);
);
</script>
</head>

<body id="__app__html"></body>

</html>


The above is just a demo to get you started, and evals as-you-type which might be dangerous while typing for loops or annoying trying to type alert("something") - You could improve the above by adding a checkbox "Autorun" and a button "Run" that becomes unhidden if autorun is unchecked.

Also make sure to use postMessage origin in production.



https://developer.mozilla.org/en-US/docs/Web/API/Window/postMessage
https://www.html5rocks.com/en/tutorials/security/sandboxed-iframes/






share|improve this answer




















  • 1





    Thank you so much it helped me a lot

    – Makeyka
    Mar 27 at 15:01















1














Instead of reloading the iframe - use postMessage.

Here's an example - having a parent page with HTML, CSS, JS textareas, and a sandboxed iframe for preview purpose:



enter image description here




index.html




<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>App</title>
<style>*margin:0;box-sizing:border-box; iframe,textareawidth:100%;min-height:3em;</style>
</head>
<body>

<textarea id="html">Hello, stack &lt;b&gt;overflow!&lt;/b&gt;</textarea>
<textarea id="css">body background: #F48024;</textarea>
<textarea id="js">document.body.innerHTML = "&lt;b&gt;World!&lt;/b&gt;";</textarea><br>
<iframe id="iframe" src="iframe.html" sandbox="allow-same-origin allow-scripts allow-modals allow-forms" frameborder="0"></iframe>

<script>
const textareas = document.querySelectorAll("#css, #html, #js");
const iframe = document.querySelector("#iframe");
const post = () => textareas.forEach(el => iframe.contentWindow.postMessage(
id: el.id,
value: el.value
, '*')); // Use 'http://example.com' instead of '*'

// Setup Events and Iframe Init
textareas.forEach(el => el.addEventListener('input', post));
iframe.addEventListener('load', post);
</script>
</body>
</html>



iframe.html




<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Iframe</title>

<style id="__app__css"></style>
<script id="__app__js"></script>
<script>
window.addEventListener('message', (evt) =>
// if (evt.origin !== "http://example.com") return; // Fix and uncomment in production
document.getElementById(`__app__$evt.data.id`).innerHTML = evt.data.value;
if (evt.data.id==='js') eval(evt.data.value);
);
</script>
</head>

<body id="__app__html"></body>

</html>


The above is just a demo to get you started, and evals as-you-type which might be dangerous while typing for loops or annoying trying to type alert("something") - You could improve the above by adding a checkbox "Autorun" and a button "Run" that becomes unhidden if autorun is unchecked.

Also make sure to use postMessage origin in production.



https://developer.mozilla.org/en-US/docs/Web/API/Window/postMessage
https://www.html5rocks.com/en/tutorials/security/sandboxed-iframes/






share|improve this answer




















  • 1





    Thank you so much it helped me a lot

    – Makeyka
    Mar 27 at 15:01













1












1








1







Instead of reloading the iframe - use postMessage.

Here's an example - having a parent page with HTML, CSS, JS textareas, and a sandboxed iframe for preview purpose:



enter image description here




index.html




<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>App</title>
<style>*margin:0;box-sizing:border-box; iframe,textareawidth:100%;min-height:3em;</style>
</head>
<body>

<textarea id="html">Hello, stack &lt;b&gt;overflow!&lt;/b&gt;</textarea>
<textarea id="css">body background: #F48024;</textarea>
<textarea id="js">document.body.innerHTML = "&lt;b&gt;World!&lt;/b&gt;";</textarea><br>
<iframe id="iframe" src="iframe.html" sandbox="allow-same-origin allow-scripts allow-modals allow-forms" frameborder="0"></iframe>

<script>
const textareas = document.querySelectorAll("#css, #html, #js");
const iframe = document.querySelector("#iframe");
const post = () => textareas.forEach(el => iframe.contentWindow.postMessage(
id: el.id,
value: el.value
, '*')); // Use 'http://example.com' instead of '*'

// Setup Events and Iframe Init
textareas.forEach(el => el.addEventListener('input', post));
iframe.addEventListener('load', post);
</script>
</body>
</html>



iframe.html




<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Iframe</title>

<style id="__app__css"></style>
<script id="__app__js"></script>
<script>
window.addEventListener('message', (evt) =>
// if (evt.origin !== "http://example.com") return; // Fix and uncomment in production
document.getElementById(`__app__$evt.data.id`).innerHTML = evt.data.value;
if (evt.data.id==='js') eval(evt.data.value);
);
</script>
</head>

<body id="__app__html"></body>

</html>


The above is just a demo to get you started, and evals as-you-type which might be dangerous while typing for loops or annoying trying to type alert("something") - You could improve the above by adding a checkbox "Autorun" and a button "Run" that becomes unhidden if autorun is unchecked.

Also make sure to use postMessage origin in production.



https://developer.mozilla.org/en-US/docs/Web/API/Window/postMessage
https://www.html5rocks.com/en/tutorials/security/sandboxed-iframes/






share|improve this answer















Instead of reloading the iframe - use postMessage.

Here's an example - having a parent page with HTML, CSS, JS textareas, and a sandboxed iframe for preview purpose:



enter image description here




index.html




<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>App</title>
<style>*margin:0;box-sizing:border-box; iframe,textareawidth:100%;min-height:3em;</style>
</head>
<body>

<textarea id="html">Hello, stack &lt;b&gt;overflow!&lt;/b&gt;</textarea>
<textarea id="css">body background: #F48024;</textarea>
<textarea id="js">document.body.innerHTML = "&lt;b&gt;World!&lt;/b&gt;";</textarea><br>
<iframe id="iframe" src="iframe.html" sandbox="allow-same-origin allow-scripts allow-modals allow-forms" frameborder="0"></iframe>

<script>
const textareas = document.querySelectorAll("#css, #html, #js");
const iframe = document.querySelector("#iframe");
const post = () => textareas.forEach(el => iframe.contentWindow.postMessage(
id: el.id,
value: el.value
, '*')); // Use 'http://example.com' instead of '*'

// Setup Events and Iframe Init
textareas.forEach(el => el.addEventListener('input', post));
iframe.addEventListener('load', post);
</script>
</body>
</html>



iframe.html




<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Iframe</title>

<style id="__app__css"></style>
<script id="__app__js"></script>
<script>
window.addEventListener('message', (evt) =>
// if (evt.origin !== "http://example.com") return; // Fix and uncomment in production
document.getElementById(`__app__$evt.data.id`).innerHTML = evt.data.value;
if (evt.data.id==='js') eval(evt.data.value);
);
</script>
</head>

<body id="__app__html"></body>

</html>


The above is just a demo to get you started, and evals as-you-type which might be dangerous while typing for loops or annoying trying to type alert("something") - You could improve the above by adding a checkbox "Autorun" and a button "Run" that becomes unhidden if autorun is unchecked.

Also make sure to use postMessage origin in production.



https://developer.mozilla.org/en-US/docs/Web/API/Window/postMessage
https://www.html5rocks.com/en/tutorials/security/sandboxed-iframes/







share|improve this answer














share|improve this answer



share|improve this answer








edited Mar 26 at 1:50

























answered Mar 26 at 1:00









Roko C. BuljanRoko C. Buljan

132k24 gold badges211 silver badges236 bronze badges




132k24 gold badges211 silver badges236 bronze badges







  • 1





    Thank you so much it helped me a lot

    – Makeyka
    Mar 27 at 15:01












  • 1





    Thank you so much it helped me a lot

    – Makeyka
    Mar 27 at 15:01







1




1





Thank you so much it helped me a lot

– Makeyka
Mar 27 at 15:01





Thank you so much it helped me a lot

– Makeyka
Mar 27 at 15:01








Got a question that you can’t ask on public Stack Overflow? Learn more about sharing private information with Stack Overflow for Teams.







Got a question that you can’t ask on public Stack Overflow? Learn more about sharing private information with Stack Overflow for Teams.



















draft saved

draft discarded
















































Thanks for contributing an answer to Stack Overflow!


  • Please be sure to answer the question. Provide details and share your research!

But avoid


  • Asking for help, clarification, or responding to other answers.

  • Making statements based on opinion; back them up with references or personal experience.

To learn more, see our tips on writing great answers.




draft saved


draft discarded














StackExchange.ready(
function ()
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f55347213%2fim-making-a-code-editor-app-that-lets-you-execute-html-css-js-code-but-javascr%23new-answer', 'question_page');

);

Post as a guest















Required, but never shown





















































Required, but never shown














Required, but never shown












Required, but never shown







Required, but never shown

































Required, but never shown














Required, but never shown












Required, but never shown







Required, but never shown







Popular posts from this blog

SQL error code 1064 with creating Laravel foreign keysForeign key constraints: When to use ON UPDATE and ON DELETEDropping column with foreign key Laravel error: General error: 1025 Error on renameLaravel SQL Can't create tableLaravel Migration foreign key errorLaravel php artisan migrate:refresh giving a syntax errorSQLSTATE[42S01]: Base table or view already exists or Base table or view already exists: 1050 Tableerror in migrating laravel file to xampp serverSyntax error or access violation: 1064:syntax to use near 'unsigned not null, modelName varchar(191) not null, title varchar(191) not nLaravel cannot create new table field in mysqlLaravel 5.7:Last migration creates table but is not registered in the migration table

용인 삼성생명 블루밍스 목차 통계 역대 감독 선수단 응원단 경기장 같이 보기 외부 링크 둘러보기 메뉴samsungblueminx.comeh선수 명단용인 삼성생명 블루밍스용인 삼성생명 블루밍스ehsamsungblueminx.comeheheheh

155 수학 과학 기타 둘러보기 메뉴eh추가해eh문서를 완성해