0

I want to have a textarea or an input where a user can write javascript code and save it (by clicking a button). Once the code is saved, it is inserted in a script and when the user clicks on "run" button then the code that he/she typed will work.

Here is an example if I wasn't specific enough:

<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>
George V
  • 59
  • 5
  • 1
    for the run part, you can do that with `eval()`. Another question is if you should do that... https://jsfiddle.net/59sbnvhy/1/ – baao Jan 06 '17 at 15:53
  • 1
    Wrap user code into a function and `eval` its `call`. As long as you do not care what users do. – PM 77-1 Jan 06 '17 at 15:53
  • 1
    The functionality you want can potentially lead to XSS attack. Please be sure why you want it. – geeksal Jan 06 '17 at 15:54

1 Answers1

1

This is not particularly secure, but you can use eval and localStorage to accomplish this:

saveBtn.onclick = function() {
  localStorage.setItem('script', editor.value);
}
runBtn.onclick = function() {
  eval(localStorage.getItem('script'))
}

Try it on JSBin.

Fabian Schultz
  • 18,138
  • 5
  • 49
  • 56