如何在网站上添加实时代码编辑器? [英] How to add a live code editor on website?
问题描述
我正在创建一个网站,需要对代码进行实时编辑(对于Java,c,python,javascript ect).我知道codemirror,我想知道如何在网站上运行代码(例如W3Schools自己尝试一下功能)并在本地运行,而不需要服务器基础架构
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
推荐答案
对于前端而言,在Stack Exchange上模拟Stack Snippets的工作原理非常简单.通常的想法是为不同部分(HTML/JS/CSS)创建文本区域,然后在要呈现它时,创建一个iframe,其内容是通过插入textarea值创建的:
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>
以上内容来自这不是Stack Snippets的工作原理-它们确实需要后端来获取表单值并构造浏览器看到的HTML响应-但这非常相似.
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.
这篇关于如何在网站上添加实时代码编辑器?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!