3

Possible Duplicate:
Is It Possible to Sandbox JavaScript Running In the Browser?

I would like to give the user the ability to input JavaScript in a textarea like this:

<!DOCTYPE html>
  <html>
    <head>
      <script>
        function lapzwans()
        {
          var d = document.getElementById("area").value;
          document.getElementById("blahblah").innerHTML = d;
        }
      </script>
    </head>
  <body>
    <h1>Javascript in Javascript</h1>
    <p>This experiment attempts to launch a script from another script.</p>
    <p>Enter your script in the text area</p>
    <textarea type="text" id="area"></textarea>
    <button onclick="lapzwans()">Click here</button>
    <p id="blahblah"></p>
    <p id="deegroller">Make this text green</p>
  </body>
</html>

I have tried this, but I get no result.
Is it impossible to do this, or am I doing things wrong?
Thanks in advance.

Community
  • 1
  • 1
David Leegwater
  • 103
  • 1
  • 4

3 Answers3

1

the eval method takes whatever string is passed to it and tries to run it.

eval("alert('foo')");

will alert "foo";

Yevgeny Simkin
  • 27,946
  • 39
  • 137
  • 236
1

You don't need to use the evil eval to do this.

function lapzwans()
{
       var d=document.getElementById("area").value;
       document.getElementById("blahblah").innerHTML=d;

       var userScript = new Function(d);
       userScript();
}
Reza Assar
  • 209
  • 1
  • 6
1

One possible answer:

eval(/* some JS here */);

Note though that what you are trying to do can be dangerous (in some cases) as you are allowing user-written arbitrary JS to be executed.

Related reading:

Community
  • 1
  • 1
Whymarrh
  • 13,139
  • 14
  • 57
  • 108