Execute JavaScript code stored as a string

前端 未结 20 831
北荒
北荒 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:09

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

提交回复
热议问题