2014-01-09 50 views
2

我試圖在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 */); 

有沒有更好的方法來做到這一點?

回答

4

有沒有方法來做到這一點在JavaScript本身(但看到加雷斯海耶斯答案的另一種選擇)。

有幾種不好的方法。

(function() { 
    var scope = Object.create(null); 
    var obscurer = {}; 
    for (var key in this) { 
    obscurer[key] = undefined; 
    } 

    with (obscurer) { 
    var isolated = function() { 
     'use strict'; 
     console.log(document); 
    }; 
    } 

    isolated.call(scope); 
})(); 

注意,因爲控制檯是沒有定義,而不是文件,你就會得到一個錯誤,雖然你可以通過在莫名其妙的對象不會阻止「控制檯」解決這個問題。你可能會發現,你需要更多的全局變量而不是你意識到的。

您也只阻止可枚舉的屬性的窗口。如果您意識到您想阻止的不可數量屬性,則必須將這些屬性添加到遮蔽器中。

當然,使用with意味着你不能使用嚴格模式更多的爲好,每個人都會看不起你..

還有更有趣的選項可用,如果您節點內工作,而比瀏覽器。

+0

Window.prototype.alert.call(window,1)繞過此沙箱。 –

+0

我得到「TypeError:window is undefined」,但是,我真的不認爲這個方法是安全的。據我所知,如果不解析輸入的代碼,你無法制作一個安全的沙箱。即使如此,仍然存在很多可能犯的錯誤(例如,人們經常忘記函數構造函數允許它們評估代碼)。 – kybernetikos

+0

這是一個Firefox特定的矢量。 –

0

它可以在沒有ECMA6的情況下通過使用包含可信需要保護代碼的IIFE完成,其中注入了不可信需求隔離代碼(請參閱示例)。

(function(injectedFunction) { 
    /* Trusted code, that needs protection from untrusted code access */ 
    var hostingFuncPrivatePrimitive = "Hello there"; 
    var hostingFuncPrivateObject = { 
     this_is_mine: true 
    }; 

    var sharedPrimitive = 'This is shared'; 
    var sharedObject = {}; 

    // Running the untrusted code: 
    injectedFunction(sharedPrimitive, sharedObject); 

    console.log("sharedObject is: " + JSON.stringify(sharedObject)); 
    console.log("hostingFuncPrivateObject is: " + 
     JSON.stringify(hostingFuncPrivateObject)); 
})(

(function(primitiveArg, objArg) { 
    /* Untrusted code that needs isolation */ 

    // 1. using primitive (legal) 
    console.log('primitiveArg is: ' + primitiveArg); 

    // 2. Writing value to given objArg (legal): 
    objArg.mumu = 'mimi'; 

    // 3. Trying to access host function variables (illegal) 
    try { 
     console.log('hostingFuncPrivatePrimitive is:' + 
      hostingFuncPrivatePrimitive); 
     hostingFuncPrivateObject.this_is_mine = false; 
    } catch (e) { 
     console.log(e); 
    } 
}) 

); 

如果你把上面的在Chrome的控制檯,您將獲得:

primitiveArg is: This is shared 
    VM117:29 ReferenceError: hostingFuncPrivatePrimitive is not defined 
      at <anonymous>:26:17 
      at <anonymous>:11:5 
      at <anonymous>:16:3 
    VM117:12 sharedObject is: {"mumu":"mimi"} 
    VM117:13 hostingFuncPrivateObject is: {"this_is_mine":true} 

P.S:我知道我遲到了,但也許這可以幫助任何人。

相關問題