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

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

当前回答

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

其他回答

Eval应该这样做。

eval(s);

该方法避免使用潜在风险的eval,提供了可调用的函数,对表达式求值器使用严格模式以获得额外的可靠性,并且比其他答案更简洁。

执行字符串命令

function string_cmd(sCmd) {
    new Function(sCmd)();
}

求字符串表达式的值

function string_exp(sCmd) {
    return Function(
        `'use strict'; 
        return (${sCmd})`
        )();
}

用法:

const result = string_exp("2+2");

string_cmd("alert(result)");

https://codepen.io/johnaweiss/pen/mdKpyZL

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

使用eval()。

W3学校评估之旅。网站有一些有用的例子的评估。Mozilla文档详细介绍了这一点。

你可能会得到很多关于安全使用的警告。不允许用户向eval()中注入任何东西,因为这是一个巨大的安全问题。

您还需要知道eval()具有不同的作用域。

不确定这是不是作弊:

window.say = function(a) { alert(a); };

var a = "say('hello')";

var p = /^([^(]*)\('([^']*)'\).*$/;                 // ["say('hello')","say","hello"]

var fn = window[p.exec(a)[1]];                      // get function reference by name

if( typeof(fn) === "function") 
    fn.apply(null, [p.exec(a)[2]]);                 // call it with params