我想要一个textarea或输入,用户可以在其中编写javascript代码并保存(通过单击按钮)。保存代码后,将其插入脚本中,当用户单击“运行”按钮时,他/她键入的代码将起作用。
如果我不够具体,这是一个例子:
<html>
<body>
<input id="editor" value="add some code here">
<!-- lets say a user types some code: -->
alert("hey");
</input>
<button id="saveBtn">Save the code</button>
<button id="runBtn">Run the code</button>
<script src='the_code_of_the_user'></script>
<script>
//Here I will just write some pseudo code because i have no idea how to do this
saveBtn.onclick = function() {
editor.insert to Script('the_code_of_the_user');
}
runBtn.onclick = function() {
run Script('the_code_of_the_user');
}
</script>
</body>
</html>
答案 0 :(得分:1)
这不是特别安全,但您可以使用eval
和localStorage
来完成此操作:
saveBtn.onclick = function() {
localStorage.setItem('script', editor.value);
}
runBtn.onclick = function() {
eval(localStorage.getItem('script'))
}