我如何执行一些JavaScript是一个字符串?
function ExecuteJavascriptString()
{
var s = "alert('hello')";
// how do I get a browser to alert('hello')?
}
我如何执行一些JavaScript是一个字符串?
function ExecuteJavascriptString()
{
var s = "alert('hello')";
// how do I get a browser to alert('hello')?
}
当前回答
使用eval函数,比如:
eval("my script here");
其他回答
function executeScript(source) {
var script = document.createElement("script");
script.onload = script.onerror = function(){ this.remove(); };
script.src = "data:text/plain;base64," + btoa(source);
document.body.appendChild(script);
}
executeScript("alert('Hello, World!');");
Stefan的回答延伸如下:
//Executes immediately function stringToFunctionAndExecute(str) { let func = new Function(str); return (func()); // <--- note the parenteces } //Executes when called function stringToFunctionOnly(str) { let func = new Function(str); return func; } // -^-^-^- Functions -^-^-^- (feel free to copy) // -v-v-v- Explanations -v-v-v- (run code to read easier) console.log('STEP 1, this executes directly when run:') let func_A = stringToFunctionAndExecute("console.log('>>> executes immediately <<<')"); console.log("STEP 2, and you can't save it in a variable, calling a() will throw an error, watch:") try { func_A(); } catch (error) { console.log('STEP ERROR, see, it failed', error) } console.log('STEP 3, but this will NOT execute directly AND you can save it for later...') let func_B = stringToFunctionOnly("console.log('>>> executes when called <<<')"); console.log("STEP 4, ...as you see, it only run when it's called for, as is done now:") func_B(); console.log('STEP 5, TADAAAAA!!')
您可以使用函数来执行它。例子:
var theInstructions = "alert('Hello World'); var x = 100";
var F=new Function (theInstructions);
return(F());
使用eval()。
W3学校评估之旅。网站有一些有用的例子的评估。Mozilla文档详细介绍了这一点。
你可能会得到很多关于安全使用的警告。不允许用户向eval()中注入任何东西,因为这是一个巨大的安全问题。
您还需要知道eval()具有不同的作用域。
New Function和apply()一起工作也可以
var a=new Function('alert(1);')
a.apply(null)