简体   繁体   中英

Execute JavaScript code stored as a string

How do I execute some JavaScript that is a string?

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

The eval<\/code> function<\/a> will evaluate a string that is passed to it.

This is because the code to be evaluated must be parsed on the spot, so that will take some computing resources.

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 . It creates a V8 virtual machine that can sandbox the execution of your code in a separate context.

Taking things a step further is vm2 which hardens vm allowing the vm to run untrusted code.

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:

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

 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

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() :

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

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>

// 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>

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

An extention of Stefan's answer<\/a> :

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

eval(s);

Remember though, that eval is very powerful and quite unsafe. 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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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