Is It Possible to Sandbox JavaScript Running In the Browser?

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

    I've been working on a simplistic js sandbox for letting users build applets for my site. Although I still face some challenges with allowing DOM access (parentNode just won't let me keep things secure =/), my approach was just to redefine the window object with some of its useful/harmless members, and then eval() the user code with this redefined window as the default scope.

    My "core" code goes like this... (I'm not showing it entirely ;)

    function Sandbox(parent){
    
        this.scope = {
            window: {
                alert: function(str){
                    alert("Overriden Alert: " + str);
                },
                prompt: function(message, defaultValue){
                    return prompt("Overriden Prompt:" + message, defaultValue);
                },
                document: null,
                .
                .
                .
                .
            }
        };
    
        this.execute = function(codestring){
    
            // here some code sanitizing, please
    
            with (this.scope) {
                with (window) {
                    eval(codestring);
                }
            }
        };
    }
    

    So, I can instance a Sandbox and use its execute() to get code running. Also, all new declared variables within eval'd code will ultimately bound to the execute() scope, so there will not be clashing names or messing with existing code.

    Although global objects will still be accesible, those which should remain unknown to the sandboxed code must be defined as proxies in the Sandbox::scope object.

    Hope this works for you.

提交回复
热议问题