I'm creating a website where live editing of code (for Java, c,python,javascript ect) is required. I'm aware of codemirror and I want to know how to run code on a website (like W3Schools try it yourself feature) and locally run instead of requiring server infrastructure
-
2Impossible. C needs a compiler, Python and Java need interpreters. You need to use a server to invoke their supporting environments. (You can do it locally, via a server on localhost) – enhzflep Apr 25 '20 at 05:38
-
2For JS it's pretty simple, you create a sandbox context within the existing tab using an iframe (that's how codepen does it IIRC). For the other langs it's not possible to run without server architecture the only way to do it would be to leverage emscripten / wasm. – marblewraith Apr 25 '20 at 05:46
1 Answers
For front-end, it's pretty easy to emulate the basics of how Stack Snippets work here on Stack Exchange. The general idea is to create textareas for the different sections (HTML/JS/CSS), then when you want to render it, create an iframe whose content is created by inserting the textarea values:
const [button, html, css, javascript, iframe] = document.querySelectorAll('button, textarea, iframe');
button.addEventListener('click', () => {
const fullHTML = `
<!doctype html><html>
<head><style>${css.value}</style></head>
<body>${html.value}<script>${javascript.value}<\/script></body>
</html>`;
iframe.src = 'data:text/html,' + encodeURIComponent(fullHTML);
});
textarea {
display: block;
}
<button>Run</button>
<textarea><span id="span">a span</span></textarea>
<textarea>span { color: green; }</textarea>
<textarea>span.onclick = () => span.style.color = 'yellow';</textarea>
<iframe sandbox="allow-scripts"></iframe>
The above is tweaked from an example from Kaiido on Meta.
This isn't exactly how Stack Snippets work - they do require a backend to take the form values and construct the HTML response the browser sees - but it's pretty similar.
For anything other than the front-end, it's a lot more complicated - you'll have to retrieve the source text the user has written, send a request to a server to run it in the correct language, then send the request back to the client and render it. For anything that a browser can't run natively already, there's no way around having "server infrastructure" to process and run code.

- 356,069
- 52
- 309
- 320