簡體   English   中英

使用內容腳本定義全局變量

[英]Use content script to define global variables

我正在創建一個Firefox擴展,我希望它的一個功能是用戶能夠將腳本或樣式表注入到特定的網站中,而不是像Greasemonkey一樣(除了僅用於一個站點)。 我正在為腳本添加一些功能,這些功能我打算從內容腳本添加到主(不安全)窗口中。 MDN博客上 ,它說他們已經更改了實施方式,因此我按照帖子中的建議將代碼基於新的實施方式,因此,我擁有以下內容:

var $jq = jQuery.noConflict();//Yes, I am also injecting jQuery at the same time
console.log("created jquery object"); //This works
exportFunction($jq, unsafeWindow, {defineAs: "$jq"});
console.log("This will never be called");

但是腳本的執行只是停止了,並且在控制台中顯示了Message: TypeError: window is null 我主要在Firefox 28中進行測試(我現在似乎無法讓Firefox for Ubuntu進行更新,並且大量的問題迫使我為此目的在VM中使用Ubuntu),但是在Nightly 31a1(Win7)中)不會注入任何東西,包括硬編碼樣式(可在FF28上使用),因此我必須在某個時候弄清楚這一點。 (PageMod代碼在這里:

var lttWorker = sdk.pageMod.PageMod({
    include:["*"],
    /*contentScriptFile: [sdk.data.url("jquery.large.js"), sdk.data.url("scripts/bootstrapper.js")],
    contentScriptWhen: "ready",*/ //This is commented to test whether it was an issue with the script. It's not.
    contentStyle: "#header_bar{background-color:green;}", //This is injected in FF28 but not 31
    attachTo: ["existing", "top"],
    onAttach: function(){desktopNotifications({title:"attached content worker", text:"The content worker has been successfully attached"})} //This is called in FF28 but not 31
});
lttWorker.on("error", function(){callError("pageWorker failed");}); //This never gets called. Ever.

如果有人有興趣)

編輯:我現在已經在Firefox 30b上嘗試過,仍然有很多問題,盡管它們似乎與FF28和31略有不同...

首先:Firefox 30及更高版本支持這些新功能。 參見@canuckistani答案。

exportFunction API太局限了,無法實際注入jQuery之類的東西,而所有復雜對象都是DOM節點或包含DOM節點。 應用於參數的結構化克隆算法根本無法實現。 該API的目的是使附加組件與頁面進行雙向通信,而不注入復雜的庫。

最好的選擇實際上是使用DOM API創建腳本標簽並將jQuery放在那。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM