Is It Possible to Sandbox JavaScript Running In the Browser?

前端 未结 15 821
北海茫月
北海茫月 2020-11-22 13:58

I\'m wondering if it\'s possible to sandbox JavaScript running in the browser to prevent access to features that are normally available to JavaScript code running in an HTML

15条回答
  •  误落风尘
    2020-11-22 14:18

    1) Suppose you have a code to execute:

    var sCode = "alert(document)";
    

    Now, suppose you want to execute it in a sandbox:

    new Function("window", "with(window){" + sCode + "}")({});
    

    These two lines when executed will fail, because "alert" function is not available from the "sandbox"

    2) And now you want to expose a member of window object with your functionality:

    new Function("window", "with(window){" + sCode + "}")({
        'alert':function(sString){document.title = sString}
    });
    

    Indeed you can add quotes escaping and make other polishing, but I guess the idea is clear.

提交回复
热议问题