How do I execute some JavaScript that is a string?
function ExecuteJavascriptString()
{
var s = \"alert(\'hello\')\";
// how do I get a browser to al
Use eval as below. Eval should be used with caution, a simple search about "eval is evil" should throw some pointers.
function ExecuteJavascriptString()
{
var s = "alert('hello')";
eval(s);
}
eval(s);
But this can be dangerous if you are taking data from users, although I suppose if they crash their own browser thats their problem.
With eval("my script here") function.
A bit like what @Hossein Hajizadeh alerady said, though in more detail:
There is an alternative to eval().
The function setTimeout() is designed to execute something after an interval of milliseconds, and the code to be executed just so happens to be formatted as a string.
It would work like this:
ExecuteJavascriptString(); //Just for running it
function ExecuteJavascriptString()
{
var s = "alert('hello')";
setTimeout(s, 1);
}
1 means it will wait 1 millisecond before executing the string.
It might not be the most correct way to do it, but it works.
Checked this on many complex and obfuscated scripts:
var js = "alert('Hello, World!');" // put your JS code here
var oScript = document.createElement("script");
var oScriptText = document.createTextNode(js);
oScript.appendChild(oScriptText);
document.body.appendChild(oScript);
new Function('alert("Hello")')();
I think this is the best way.