Execute JavaScript code stored as a string

2018-12-31 16:20发布

问题:

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\')?
}

回答1:

With eval(\"my script here\") function.



回答2:

You can execute it using a function. Example:

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

var F=new Function (theInstructions);

return(F());


回答3:

The eval function will evaluate a string that is passed to it.

But the use of eval can be dangerous, so use with caution.

Edit: annakata has a good point -- Not only is eval dangerous, it is slow. This is because the code to be evaluated must be parsed on the spot, so that will take some computing resources.



回答4:

Use eval().

W3 Schools tour of eval. Site has some usable examples of eval. The Mozilla documentation covers this in detail.

You will probably get a lot of warnings about using this safely. do NOT allow users to inject ANYTHING into eval() as it is a huge security issue.

You\'ll also want to know that eval() has a different scope.



回答5:

Try this:

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

Personally I didnt test it, but seems to work.



回答6:

A bit like what @Hossein Hajizadeh alerady said, though in more detail:

There is an alternative to eval().

The function setTimeout() 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.

It would work like this:

ExecuteJavascriptString(); //Just for running it

function ExecuteJavascriptString()
{
    var s = \"alert(\'hello\')\";
    setTimeout(s, 1);
}

1 means it will wait 1 millisecond before executing the string.

It might not be the most correct way to do it, but it works.



回答7:

Use eval as below. Eval should be used with caution, a simple search about \"eval is evil\" should throw some pointers.

function ExecuteJavascriptString()
{
    var s = \"alert(\'hello\')\";
    eval(s);
}


回答8:

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


回答9:

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


回答10:

eval(s);

But this can be dangerous if you are taking data from users, although I suppose if they crash their own browser thats their problem.



回答11:

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


回答12:

eval should do it.

eval(s);


回答13:

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.



回答14:

New Function and apply() together works also

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


回答15:

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.



回答16:

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


回答17:

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

I think this is the best way.



标签: javascript