2015-05-04 54 views
4

假設frame.html Firefox SDK插件裏面的數據文件夾, 如何附加iframe並定義frame.html作爲它的源代碼?如何使用Firefox SDK插件將iframe附加到託管頁面?

附加信息: 由於CPS,它不可能使用內聯源,所以我不能使用data.load('frame.html'),我需要使用的文件的URL的:

的lib/main.js

tabs.activeTab.attach({ 
    contentScriptFile: [self.data.url("js/appender.js") ], 
    attachTo: 'top', 
    contentScriptOptions: { 
    scriptUrl: self.data.url("js/sandbox.js"), 
    imageUrl: self.data.url("image.jpg") 
    frameUrl: self.data.url("sandbox.html") 
    } 
}); 

數據/ appender.js

var scriptTag = document.createElement("script"); 
    scriptTag.src = self.options.scriptUrl; 
    document.body.appendChild(scriptTag); // worked fine 

    var imageTag = document.createElement("image"); 
    imageTag.src = self.options.imageUrl; 
    document.body.appendChild(imageTag); // worked fine 

    var iframeTag = document.createElement("iframe"); 
    iframeTag.src = self.options.frameUrl; 
    document.body.appendChild(iframeTag); // the html tag of iframe is empty 

回答

3

這是因爲它好好嘗試一下讓內容腳本加載資源的URL作爲I幀Firefox的安全政策的空白。解決方案可以直接從後臺腳本中設置,因此您需要使用低級別的sdk。

var { viewFor } = require("sdk/view/core"); 
var tab_utils = require("sdk/tabs/utils"); 

var iframe = viewFor(tab).linkedBrowser._contentWindow.document.querySelector('iframe[src="' + self.data.url("sandbox.html") + '"]') 
iframe.contentWindow.location.href = iframe.getAttribute("src") 

所以工作完全代碼是這樣:

數據/ appender.js

var iframeTag = document.createElement("iframe"); 
iframeTag.src = self.options.frameUrl; 
document.body.appendChild(iframeTag); // the html tag of iframe is empty 

// note that the iframe is attached after the content ready event, so you have to inform the background when it can start working with the iframe 
self.port.emit("attached", true); 

main.js

tabs = require("sdk/tabs") 
self = require("sdk/self") 

var { viewFor } = require("sdk/view/core"); 
tab_utils = require("sdk/tabs/utils"); 

tabs.on("ready", function(tab) { 
    var worker = tab.attach({ 
    contentScriptFile: [self.data.url("js/appender.js") ], 
    attachTo: 'top', 
    contentScriptOptions: { 
     frameUrl: self.data.url("sandbox.html") 
    } 
    }); 

    worker.port.on('attached', function() { 
    reinitIframe(tab) 
    }); 

    function reinitIframe(tab) { 
    var iframe = viewFor(tab).linkedBrowser._contentWindow.document.querySelector('iframe[src="' + self.data.url("sandbox.html") + '"]') 
    iframe.contentWindow.location.href = iframe.getAttribute("src") 
    } 
}) 

你可能需要在cross-process wrapper爲了使其在未來的電解版火狐中工作

+0

我對此表示讚賞。謝謝 – Reyraa

+0

你讓我們從頭痛中解脫出來。 –

+0

我用過這個,工作。但爲什麼我不能postMessage這個iframe? – Reyraa

0

找到了一個更好的方法。您添加一個空白併爲load事件附加一個事件偵聽器。然後,您可以像平常一樣輕鬆地將所需的任何元素添加到iframe中。

在您的內容腳本包含此:

var iframe = document.createElement('iframe'), 
    div = document.createElement('div'); 
div.textContent('Hello World'); 
document.body.appendChild(iframe); 
iframe.addEventListener('load', function(){ 
    this.contentWindow.document.body.appendChild(div) 
}) 
相關問題