Execute JavaScript code stored as a string

前端 未结 20 795
北荒
北荒 2020-11-22 08:58

How do I execute some JavaScript that is a string?

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


        
相关标签:
20条回答
  • 2020-11-22 09:17

    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.

    0 讨论(0)
  • 2020-11-22 09:18

    New Function and apply() together works also

    var a=new Function('alert(1);')
    a.apply(null)
    
    0 讨论(0)
  • 2020-11-22 09:20

    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.

    • https://nodejs.org/api/vm.html - Official nodejs/vm

    • https://github.com/patriksimek/vm2 - Extended vm2

    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.
    
    0 讨论(0)
  • 2020-11-22 09:24

    eval should do it.

    eval(s);
    
    0 讨论(0)
  • 2020-11-22 09:24
    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.

    0 讨论(0)
  • 2020-11-22 09:24

    Using both eval and creating a new Function to execute javascript comes with a lot of security risks.

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

    I prefer this method to execute the Javascript I receive as a string.

    0 讨论(0)
提交回复
热议问题