gpt4 book ai didi

javascript - 在 Firefox 中与 Web 内容(页面对象)共享插件对象(内容脚本)

转载 作者:塔克拉玛干 更新时间:2023-11-02 21:16:36 25 4
gpt4 key购买 nike

我花了几天时间尝试将我的一个 Firefox for Android 扩展对象与我也从我的扩展打开的网页(声明为资源)共享。问题是我已经阅读了很多关于 the last year's changes 的内容关于 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 Android 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();

它奏效了。

关于javascript - 在 Firefox 中与 Web 内容(页面对象)共享插件对象(内容脚本),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28653825/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com