我如何执行一些JavaScript是一个字符串?

function ExecuteJavascriptString()
{
    var s = "alert('hello')";
    // how do I get a browser to alert('hello')?
}

当前回答

有点像@Hossein Hajizadeh alerady说的,不过更详细:

有一个替代eval()的方法。

函数setTimeout()被设计为在毫秒间隔后执行一些东西,而要执行的代码恰好格式化为字符串。

它是这样工作的:

ExecuteJavascriptString ();//只是为了运行它 ExecuteJavascriptString()函数 { Var s = "alert('hello')"; setTimeout (s, 1); }

1表示它将在执行字符串前等待1毫秒。

这可能不是最正确的方法,但它确实有效。

其他回答

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!!')

eval(s);

但如果你从用户那里获取数据,这可能是危险的,尽管我想如果他们自己的浏览器崩溃了,那是他们的问题。

同时使用eval和创建一个新函数来执行javascript会带来很多安全风险。

const script = document.createElement("script");
const stringJquery = '$("#button").on("click", function() {console.log("hit")})';
script.text = stringJquery;
document.body.appendChild(script);

我更喜欢这个方法来执行我作为字符串接收的Javascript。

eval函数将对传递给它的字符串求值。

但是eval的使用是超级危险和缓慢的,所以要谨慎使用。

检查了许多复杂和混乱的脚本:

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);