簡體   English   中英

在Firefox中與Web內容(頁面對象)共享插件對象(內容腳本)

[英]Sharing addon objects (content scripts) with Web content (page objects) in Firefox

我花了幾天時間嘗試與我的擴展程序(聲明為資源)打開的網頁共享我的一個Firefox for Android擴展程序對象。 事情是我已經閱讀了很多關於去年關於unsafewindow 的變化 ,所以我嘗試了一個非常小的例子,新的功能,但沒有工作。 我復制了這些示例,我也嘗試了自己的所有,但沒有辦法復制具有功能的現有對象。 看,我在內容窗口中有一個非常大的對象要克隆,但我決定用一個小對象進行測試:

//From addon
var dog = {
    name: 'Spike',
    woof: function(){alert('woof woof!')}
};

之后我嘗試將此對象復制到活動窗口中:

//From addon
var contentWindow = window.BrowserApp.selectedBrowser.contentWindow;
contentWindow.dog = Components.utils.cloneInto(
    dog, 
    contentWindow, 
    {cloneFunctions: true}
);

之后,我嘗試檢查真正復制的內容:

alert(contentWindow.dog); //Shows: [object Object]
alert(contentWindow.dog.name); //Shows: Spike
alert(contentWindow.dog.woof); //Shows: undefined

所以,即使我聲明“cloneFunctions:true”,我也可以克隆對象而不是函數。

我還嘗試創建一個空對象,然后分配函數(在我這么大的原始對象中有很多工作思路),並且不起作用:

function greetme(user) {
    return "cheers " + user;
}
var foo = Components.utils.createObjectIn(contentWindow,{defineAs: "foo"});
Components.utils.exportFunction(greetme, foo, {defineAs: "greetme"}); 
//foo is not an object in current window

所以...任何想法都是受歡迎的,我真的不知道該怎么做,因為理論和給出的例子不再適用。

謝謝(很多)提前!!

https://blog.mozilla.org/addons/2014/04/10/changes-to-unsafewindow-for-the-add-on-sdk/

您的代碼已經或多或少已經正確,但是,您遇到了XRay包裝器的問題。 而且,為了讓內容窗口(網站)真正看到你的dog ,你還需要放棄內容窗口上的XRay包裝器。

我用當前的Firefox for Nightly測試了以下內容(對不起,我發布的Firefox沒有配置為遠程調試)。

在主進程(使用WebIDE)中執行此操作:

var dog = {
  name: 'Spike',
  woof: function () {
    alert(contentWindow.document.title + "\n" + this.name + ': woof woof!');
  }
};

var contentWindow = BrowserApp.selectedBrowser.contentWindow;

// Need to unwrap this, so that we can actually set properties on the
// object itself and not just the wrapper. Aka. make "dog" visible to
// the actual script.
var unsafeWindow = Components.utils.waiveXrays(contentWindow);

// Define Window.dog (on the unsafe window, so that the website code
// can actually see it).
unsafeWindow.dog = Components.utils.cloneInto(dog, contentWindow, {
  cloneFunctions: true
});

然后我切換到實際的選項卡並測試:

dog.woof();

它奏效了。

暫無
暫無

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

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