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

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

1 Comment

Yes. This is what I wanted, thank you alot.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.