【问题标题】:Sharing addon objects (content scripts) with Web content (page objects) in Firefox在 Firefox 中与 Web 内容(页面对象)共享插件对象(内容脚本)
【发布时间】:2015-02-22 22:39:03
【问题描述】:

我花了几天时间尝试将我的一个 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/

【问题讨论】:

    标签: javascript firefox firefox-addon firefox-addon-sdk


    【解决方案1】:

    您的代码或多或少已经正确,但是,您在使用 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();
    

    它奏效了。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-03-09
      • 1970-01-01
      • 2011-10-14
      相关资源
      最近更新 更多