每个HTML、CSS和JS都有3个文本区域。例如,在CSS & HTML文本区域内键入:html { background: green; }
将使iframe变为绿色,然后您可以将绿色更改为蓝色,而无需刷新页面,而iframe就会变成蓝色。但是,当我编写JS代码时,它只执行一次,例如,document.write("1");
在iframe中打印1,但是如果我添加另一个document.write("2");
,它将iframe保留为空。
// 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());
});
我希望在iframe中每次添加JS代码时都会出现新的输出,就像它对HTML和CSS所做的一样。请在这里试用一下:https://online-code-editor.netlify.com/
(不要介意消失的图标)
更新:
我发现这个document.getElementById("browserFrame").contentDocument.location.reload(true);
重新加载我的iframe,但是太快了,只有单击RUN才能使它工作吗?
或者说增加了一些延迟
发布于 2019-03-25 17:00:50
而不是重新加载iframe -使用postMessage
。
下面是一个示例--有一个带有HTML、CSS、JS textarea
的父页面和一个沙箱iframe
用于预览目的:
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,textarea{width:100%;min-height:3em;}</style>
</head>
<body>
<textarea id="html">Hello, stack <b>overflow!</b></textarea>
<textarea id="css">body {background: #F48024;}</textarea>
<textarea id="js">document.body.innerHTML = "<b>World!</b>";</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>
以上只是一个让你开始的演示,当输入eval
循环或烦人的尝试输入alert("something")
时,您可以添加一个复选框" autorun“和一个按钮"Run”,如果不选中自动运行,它就变成了unhidden
,这可能是危险的。
还要确保在生产中使用postMessage origin
。
https://developer.mozilla.org/en-US/docs/Web/API/Window/postMessage
https://www.html5rocks.com/en/tutorials/security/sandboxed-iframes/
https://stackoverflow.com/questions/55347213
复制相似问题