问题
I trying to create a sandbox module that can take a object and prevent that object's code reference to window.
here is how it work in concept.
var sand = function(window) {
var module = {
say: function() {
console.log(window.location);
}
};
return module;
}
sand({}).say(); // window.location is undefine
This doesn't work if the object is pass-in
var $sand = (function(){
return function(obj, context) {
return (function(obj, window) {
window.module = {};
// doesn't work even copy object
for (p in obj) {
window.module[p] = obj[p];
}
console.log(window.location); // undefine
return window.module;
}(obj, context));
};
}());
var module = {
say: function() {
console.log(window.location);
}
};
$sand(module, {}).say(); // still reference to window.location
How can i make this pattern work?
回答1:
As long as you don't have a variable shadowing window
in the scope of your function, the function will be able to access window
. Even if you had a variable called window
, the code will still be able to access the properties by simply omitting window.
.
(function(window) {
console.log(window.location); //undefined
console.log(location); //this will still work
})({ });
In other words, sandboxing JavaScript in a browser environment is not possible like this.
回答2:
In your first example, the only reason window is undefined
is because you are passing in an empty object and calling the argument window
, so it is hiding the real window
.
Also, you can always get access to the window object by hoisting the this
variable inside a closure, like so:
console.log ( ( function () { return this; } )() );
So even if you somehow manage to block window
, it's trivial to get it back again.
回答3:
If you define the function outside your sandbox, the context will be the current one, and you can't really do otherwise.
If you really want to do some sandboxing, then you should use iframes to achieve that. Take a look at https://github.com/substack/vm-browserify it is a browser version of the vm
module of node, you should be able to extract some good pieces of work, and avoiding eval
which is not really clean for what you want to do.
来源:https://stackoverflow.com/questions/10230532/javascript-sandbox-a-module-to-prevent-reference-to-window