簡體   English   中英

執行存儲為字符串的 JavaScript 代碼

[英]Execute JavaScript code stored as 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");

您可以使用函數執行它。 例子:

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

var F=new Function (theInstructions);

return(F());

eval<\/code>函數<\/a>將評估傳遞給它的字符串。

但是使用eval<\/code>可能很危險<\/a>,因此請謹慎使用。

編輯:<\/strong> annakata 有一個好處—— eval<\/code>不僅危險<\/em><\/strong>,而且速度很慢<\/em><\/strong>。 這是因為要評估的代碼必須在現場解析,這樣會占用一些計算資源。

試試這個:

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

對於使用 node 並且關心eval()的上下文含義的用戶,nodejs 提供了vm 它創建了一個 V8 虛擬機,可以在單獨的上下文中對代碼的執行進行沙箱化處理。

更進一步的是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.

有點像@Hossein Hajizadeh<\/em> alerady 所說的,雖然更詳細:

eval()<\/code>有一個替代方案。

函數setTimeout()<\/code>旨在在毫秒間隔后執行某些操作,而要執行的代碼恰好被格式化為字符串。

它會像這樣工作:

1<\/code>表示它將在執行字符串之前等待 1 毫秒。

這可能不是最正確的方法,但它確實有效。

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

我認為這是最好的方法。

在許多復雜和混淆的腳本上檢查了這一點:

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

如果您想在特定時間后執行特定命令(即字符串) - 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 和apply()<\/a>也可以一起使用

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

我正在回答類似的問題,並獲得了另一個想法,即如何在不使用eval()的情況下實現這一目標:

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

在上面的代碼中,您基本上創建了包含腳本的 Blob,以便創建對象 URL(在瀏覽器內存中表示文件或 Blob 對象)。 由於<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);

但是,如果您從用戶那里獲取數據,這可能會很危險,盡管我認為如果他們自己的瀏覽器崩潰,那就是他們的問題。

不確定這是否作弊:

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

一個可以使用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                                

同時使用 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);

此方法避免使用具有潛在風險的評估,提供可調用函數,在表達式評估器上使用嚴格模式以獲得額外的可靠性,並且比其他答案更簡潔。

執行字符串命令

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

評估字符串表達式

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

用法:

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

string_cmd("alert(result)");

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

eval(s);

但請記住,eval 非常強大且非常不安全。 您最好確信您正在執行的腳本是安全的,並且用戶不可變。

使用字符串運行代碼

 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