Is It Possible to Sandbox JavaScript Running In the Browser?

前端 未结 15 936
北海茫月
北海茫月 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:21

    You can wrap the user's code in a function that redefines forbidden objects as parameters -- these would then be undefined when called:

    (function (alert) {
    
    alert ("uh oh!"); // User code
    
    }) ();
    

    Of course, clever attackers can get around this by inspecting the Javascript DOM and finding a non-overridden object that contains a reference to the window.


    Another idea is scanning the user's code using a tool like jslint. Make sure it's set to have no preset variables (or: only variables you want), and then if any globals are set or accessed do not let the user's script be used. Again, might be vulnerable to walking the DOM -- objects that the user can construct using literals might have implicit references to the window object that could be accessed to escape the sandbox.

提交回复
热议问题