我試圖在JavaScript中的空隔離執行上下文中執行一段代碼。在下面的示例中,我試圖隔離isolated
執行範圍。我想要做的就是在上下文中執行的功能中沒有全局變量英寸JavaScript中的隔離執行上下文
(function() {
'use strict';
var scope = Object.create(null);
var isolated = function() {
'use strict';
console.log(document); // Trying to get undefined
// but traces `document`.
};
isolated.call(scope);
})();
我認爲這是簡單的抵消全局變量,但有太多!
var isolated = function(window, document, location /* etc */) {
// ...
};
isolated.call(scope, undefined, undefined, undefined /* etc */);
有沒有更好的方法來做到這一點?
Window.prototype.alert.call(window,1)繞過此沙箱。 –
我得到「TypeError:window is undefined」,但是,我真的不認爲這個方法是安全的。據我所知,如果不解析輸入的代碼,你無法制作一個安全的沙箱。即使如此,仍然存在很多可能犯的錯誤(例如,人們經常忘記函數構造函數允許它們評估代碼)。 – kybernetikos
這是一個Firefox特定的矢量。 –