2015-05-31 28 views
9

我正在構建一個運行不受信任的代碼的沙箱。出於這個原因,我創建了一個沙盒iframe(其​​屬性中只設置了allow-scripts權限)以保護原點,然後在該iframe中創建一個web-worker以確保單獨的線程並防止凍結主應用程序例如在不可信代碼具有無限循環的情況下。如何在沙盒iframe中創建工作人員?

問題是,如果我嘗試通過https加載沙箱,最近的Google Chrome不允許創建工作人員。在其他瀏覽器上它可以工作,而且如果我通過http加載Chrome中的沙箱,它也可以工作。

下面是代碼:

的index.html:

<!DOCTYPE html> 
<html> 
    <head> 
    <title>Sandbox test</title> 
    <script type="text/javascript" src="main.js"></script> 
    </head> 
    <body></body> 
</html> 

main.js:

// determining absolute path of iframe.html 
var scripts = document.getElementsByTagName('script'); 
var url = scripts[scripts.length-1].src 
    .split('/') 
    .slice(0, -1) 
    .join('/')+'/iframe.html'; 

window.addEventListener("load", function() { 
    var iframe = document.createElement('iframe'); 
    iframe.src = url; 
    iframe.sandbox = 'allow-scripts'; 
    iframe.style.display = 'none'; 
    document.body.appendChild(iframe); 

    window.addEventListener('message', function(e) { 
     if (e.origin=='null' && e.source == iframe.contentWindow) { 
      document.write(e.data.text); 
     } 
    }); 
}, 0); 

Iframe.html的:

<script src="iframe.js"></script> 

iframe.js:

var code = 'self.postMessage({text: "sandbox created"});'; 
var url = window.URL.createObjectURL(
    new Blob([code], {type: 'text/javascript'}) 
); 

var worker = new Worker(url); 

// forwarding messages to parent 
worker.addEventListener('message', function(m) { 
    parent.postMessage(m.data, '*'); 
}); 

演示:

http://asvd.github.io/sandbox/index.html - HTTP演示(作品無處不在)

https://asvd.github.io/sandbox/index.html - HTTPS演示(在Chrome中不工作)

https://github.com/asvd/asvd.github.io/tree/master/sandbox - source(e Xactly公司在這個問題內聯)

谷歌瀏覽器則抱怨:

混合內容:在頁面「https://asvd.github.io/sandbox/iframe.html」裝載了HTTPS,但要求一個不安全的工人腳本的「blob:空/ a9f2af00-47b1- 45c1-874e-be4003523794' 。此請求已被阻止;內容必須通過HTTPS提供。

我也嘗試通過https從文件而不是blob加載工作人員代碼,但這在任何地方都是不允許的,因爲我無法從iframe中訪問相同來源的文件。

我想知道是否有機會在Chrome中使這樣的沙箱工作,而不會將iframe的權限添加到allow-same-origin

回答

3

正如您所發現的,Chrome不會讓您從https頁面訪問非https內容(例如數據blob),還會將blob URL視爲不是https。如果沒有allow-same-origin,則無法加載任何域中的任何工作腳本文件。

我唯一的建議是讓iframe從單獨的https服務的域(/子域)提供服務,然後同時使用allow-scriptsallow-same-origin。由於處於單獨的域中,iframe中的代碼仍然無法訪問父頁面的DOM /數據。

+1

這將工作一次性的解決方案,但我保持了庫(https://github.com/asvd/jailed) - 因此,我試圖找到沒有使用戶有一個單獨的域的解決方案。 – asvd