简体   繁体   English

执行存储为字符串的 JavaScript 代码

[英]Execute JavaScript code stored as a string

How do I execute some JavaScript that is a string?我如何执行一些 JavaScript 是一个字符串?

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

使用eval<\/code><\/a>函数,例如:

eval("my script here");

You can execute it using a function.您可以使用函数执行它。 Example:例子:

var theInstructions = "alert('Hello World'); var x = 100";

var F=new Function (theInstructions);

return(F());

Try this:试试这个:

  var script = "<script type='text/javascript'> content </script>";
  //using jquery next
  $('body').append(script);//incorporates and executes inmediatelly

For users that are using node and that are concerned with the context implications of eval() nodejs offers vm .对于使用 node 并且关心eval()的上下文含义的用户,nodejs 提供了vm It creates a V8 virtual machine that can sandbox the execution of your code in a separate context.它创建了一个 V8 虚拟机,可以在单独的上下文中对代码的执行进行沙箱化处理。

Taking things a step further is vm2 which hardens vm allowing the vm to run untrusted code.更进一步的是vm2 ,它强化了vm ,允许 vm 运行不受信任的代码。

const vm = require('vm');

const x = 1;

const sandbox = { x: 2 };
vm.createContext(sandbox); // Contextify the sandbox.

const code = 'x += 40; var y = 17;';
// `x` and `y` are global variables in the sandboxed environment.
// Initially, x has the value 2 because that is the value of sandbox.x.
vm.runInContext(code, sandbox);

console.log(sandbox.x); // 42
console.log(sandbox.y); // 17

console.log(x); // 1; y is not defined.

A bit like what @Hossein Hajizadeh<\/em> alerady said, though in more detail:有点像@Hossein Hajizadeh<\/em> alerady 所说的,虽然更详细:

There is an alternative to eval()<\/code> . eval()<\/code>有一个替代方案。

The function setTimeout()<\/code> 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.函数setTimeout()<\/code>旨在在毫秒间隔后执行某些操作,而要执行的代码恰好被格式化为字符串。

It would work like this:它会像这样工作:

 ExecuteJavascriptString(); \/\/Just for running it function ExecuteJavascriptString() { var s = "alert('hello')"; setTimeout(s, 1); }<\/code><\/pre>

1<\/code> means it will wait 1 millisecond before executing the string. 1<\/code>表示它将在执行字符串之前等待 1 毫秒。

It might not be the most correct way to do it, but it works.这可能不是最正确的方法,但它确实有效。

"

new Function('alert("Hello")')();

我认为这是最好的方法。

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

If you want to execute a specific command (that is string) after a specific time - cmd=your code - InterVal=delay to run如果您想在特定时间后执行特定命令(即字符串) - cmd=您的代码 - InterVal=delay to run

 function ExecStr(cmd, InterVal) {
    try {
        setTimeout(function () {
            var F = new Function(cmd);
            return (F());
        }, InterVal);
    } catch (e) { }
}
//sample
ExecStr("alert(20)",500);

New Function and apply()<\/a> together works also New Function 和apply()<\/a>也可以一起使用

var a=new Function('alert(1);')
a.apply(null)

I was answering similar question and got yet another idea how to achieve this without use of eval() :我正在回答类似的问题,并获得了另一个想法,即如何在不使用eval()的情况下实现这一目标:

const source = "alert('test')";
const el = document.createElement("script");
el.src = URL.createObjectURL(new Blob([source], { type: 'text/javascript' }));
document.head.appendChild(el);

In the code above you basically create Blob, containing your script, in order to create Object URL (representation of File or Blob object in browser memory).在上面的代码中,您基本上创建了包含脚本的 Blob,以便创建对象 URL(在浏览器内存中表示文件或 Blob 对象)。 Since you have src property on <script> tag, the script will be executed the same way as if it was loaded from any other URL.由于<script>标记上有src属性,因此脚本的执行方式与从任何其他 URL 加载的方式相同。

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

但是,如果您从用户那里获取数据,这可能会很危险,尽管我认为如果他们自己的浏览器崩溃,那就是他们的问题。

Not sure if this is cheating or not:不确定这是否作弊:

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

One can use mathjs<\/a>一个可以使用mathjs<\/a>

Snippet from above link:来自以上链接的片段:

// evaluate expressions
math.evaluate('sqrt(3^2 + 4^2)')        // 5
math.evaluate('sqrt(-4)')               // 2i
math.evaluate('2 inch to cm')           // 5.08 cm
math.evaluate('cos(45 deg)')            // 0.7071067811865476

// provide a scope
let scope = {
    a: 3,
    b: 4
}
math.evaluate('a * b', scope)           // 12
math.evaluate('c = 2.3 + 4.5', scope)   // 6.8
scope.c                                

Using both eval and creating a new Function to execute javascript comes with a lot of security risks.<\/a>同时使用 eval 和创建一个新的 Function 来执行 javascript 会带来很多安全风险。<\/a>

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

This method avoids use of potentially-risky eval, provides callable functions, uses strict mode on the expression evaluator for extra reliability, and less verbose than other answers.此方法避免使用具有潜在风险的评估,提供可调用函数,在表达式评估器上使用严格模式以获得额外的可靠性,并且比其他答案更简洁。

execute a string command执行字符串命令

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

evaluate a string expression评估字符串表达式

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

usage:用法:

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

string_cmd("alert(result)");

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

eval(s);

Remember though, that eval is very powerful and quite unsafe.但请记住,eval 非常强大且非常不安全。 You better be confident that the script you are executing is safe and unmutable by users.您最好确信您正在执行的脚本是安全的,并且用户不可变。

Run code using string使用字符串运行代码

 function runMe(x,y,z){ console.log(x); console.log(y); console.log(z); } // function name and parameters to pass var fnstring = "runMe"; var fnparams = [1, 2, 3];//<--parameters // find object var fn = window[fnstring]; // is object a function? if (typeof fn === "function") fn.apply(null, fnparams);//<--apply parameter
 enter code here

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM