在我的网站上像Stackoverflow一样运行Java代码

问题描述 投票:1回答:2

[在我的网站上,我有一些Javascript代码需要在我的网站上直接运行。例如,使用此代码段:

console.log("Hello World")

我有一个“运行代码段”按钮。我想要做的是:当我单击按钮时,代码将在我的Web上立即执行。就像Stackoverflow上的此功能一样:enter image description here

我该怎么办?在此先感谢:D

javascript jsfiddle
2个回答
0
投票

首先,您可以获取用户键入的代码,那么您需要将其存储在变量中,最后您使用eval(code); //the code that you stored before

然后该代码将在当前页面中执行。


0
投票

这里是您可以开始的简单演示。通常,这不被认为是安全的,并且要准备好投入生产,您将必须认真考虑隔离执行上下文。

我只是想为您提供一个切入点。您可以在这里执行您的JS。

function runCode() {

    var console = {

       log:  function (val) {
          let paragraph = document.getElementById("console");
          let text = document.createTextNode(val);
          
          paragraph.appendChild(text);
          paragraph.appendChild(document.createElement('br'));
       }
    }

 
    var code = document.getElementById('myjs').value;
 
 
  eval(code);
}
<textarea id="myjs" style="width: 320px; height: 120px">
   //Sample code
   function add(a, b) {
      return a + b;
   }

   let c = add(9, 1);
   
   console.log('9 + 1 = ' + c);
   
</textarea>


<input type="button" value = "Run" onClick="runCode()">

<p id="console"></p>
© www.soinside.com 2019 - 2024. All rights reserved.