Andrew Andrew - 1 year ago 75
Javascript Question

How to execute javascript supplied by a text field

I am working on extending our companies analytics web application by adding the ability to do fully custom queries. As part of that, I have added a text field to the UI where a user will be able to type javascript. I am then looking to have the application take that javascript that was typed into the text field, execute it, and store the result into a variable.

In HTML, I have this:

<div class="div1">
<div class="div1-1">
<textarea name="customquery" id="customQuery" placeholder="Javascript function body where one can define a query script." />

In my javascript file, I am looking for something that will allow me to do this:

var result = /* result of executing java script from the 'customquery' textarea*/

This will be part of a large javascript function that is triggered when the user clicks the 'submit' button on the web application.

How can I do this?

Answer Source

It sounds as if you are looking for the eval-function. It takes a string, executes it as Javascript and returns the result if there is any.

I assume that you are aware of possible consequences for usability and security.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download