如何在<browser>元素中操作窗口原型?</browser>

时间:2011-11-28 07:10:38

标签: firefox-addon xul xpcom

我现在正在做的是:

加载<browser src="..." />后,我会将数据附加到.contentWindow

frame.addEventListener("load",function(){
    this.contentWindow.someMethod = function(){};
},true);

现在我想知道是否有办法更早地进入<browser>的窗口原型,或任何Window原型,例如我可以在“当前”窗口中执行:

// [W]indow is the constructor
Window.prototype.test = function(){ alert("hello"); };
// [w]indow is the instance
window.test();

1 个答案:

答案 0 :(得分:4)

目前有两种方法可以在任何JavaScript代码运行之前将属性注入窗口。通常,content-document-global-created notification更简单。另一个是implementing nsIDOMGlobalPropertyInitializer interface。两者都允许您在加载新窗口时以及在该窗口运行JavaScript代码之前收到通知。

以下是使用观察者通知执行此操作的近似代码:

const Cc = Components.classes;
const Ci = Components.interfaces;
const Cu = Components.utils;
Cu.import("resource://gre/modules/XPCOMUtils.jsm");

var myObserver =
{
  QueryInterface: XPCOMUtils.generateQI([Ci.nsIObserver, Ci.nsISupportsWeakReference]),

  observe: function(subject, topic, data)
  {
    if (topic == "content-document-global-created" &&
        subject instanceof Ci.nsIDOMWindow &&
        subject.location.hostname == "example.com")
    {
      XPCNativeWrapper.unwrap(subject).someMethod = function() {};
    }
  }
};

var observerService = Cc["@mozilla.org/observer-service;1"]
                        .getService(Ci.nsIObserverService);
observerService.addObserver(myObserver, "content-document-global-created", true);