R. Baauw
R. Baauw

Reputation: 51

Run the code inside of string Javascript

I have a variable (string) in Javascript, in which you for example have this text:

"document.getElementById('tekst').innerHTML = 'Probeer opnieuw!';"

I got this variable using Ajax and PHP, but that is not where my (possibly very easy) question is about.

Say I want to use this code as code itself, not as a string, so instead of this being a string I would like the code inside of it to be executed.

How can I possibly do this?

Thanks in advance

Upvotes: 0

Views: 83

Answers (3)

Ouroborus
Ouroborus

Reputation: 16875

Don't do this. It's a security nightmare.

If you really must do this, use eval() as in:

eval("document.getElementById('tekst').innerHTML = 'Probeer opnieuw!';");

Considering your example and explanation, I suspect that you are retrieving a url whose contents consist entirely of javascript. The problem you've run across is that the method you are using to retrieve that url gives you a string containing that javascript. I believe that it's intended for you to instead use a <script> element to load that code. To do so dynamically:

var script = document.createElement("script");
script.src = "url/to/your/javascript";
document.getElementByTagName('body')[0].appendChild(script);

Upvotes: 3

Rounin
Rounin

Reputation: 29463

Here is an alternative to using eval() :

var stringContainingJavascript = "document.getElementById('tekst').innerHTML = 'Probeer opnieuw!';"

var body = document.getElementsByTagName('body')[0];

var paragraph = document.createElement('p');
paragraph.id = 'tekst';
body.appendChild(paragraph);

var script = document.createElement('script');
var scriptText = document.createTextNode(stringContainingJavascript);
script.appendChild(scriptText);
body.appendChild(script);

The script above creates a <p> element and gives it id="tekst", before appending the <p> to the <body> of the document.

The same script then creates a <script> element and appends the string to it, before appending the <script> to the <body> of the document.

Upvotes: 0

jessegavin
jessegavin

Reputation: 75650

You can use the eval() method. But don't do it if you don't have to. And if you do have to, make sure you know what you're doing.

eval("document.getElementById('tekst').innerHTML = 'Probeer opnieuw!';")

Upvotes: 1

Related Questions