繁体   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