Javascript 使用nsIDOMGlobalPropertyInitializer将对象注入特定页面
我需要使用nsIDOMGlobalPropertyInitializer将名为“smth”的对象注入到带有特定URL的页面上的窗口中。有什么方法可以实现这一点吗?如果window.smth在其他页面上返回undefined,就可以了Javascript 使用nsIDOMGlobalPropertyInitializer将对象注入特定页面,javascript,firefox-addon,xpcom,Javascript,Firefox Addon,Xpcom,我需要使用nsIDOMGlobalPropertyInitializer将名为“smth”的对象注入到带有特定URL的页面上的窗口中。有什么方法可以实现这一点吗?如果window.smth在其他页面上返回undefined,就可以了 // currently init: function(aWindow) { let self = this; let window = XPCNativeWrapper.unwrap(aWindow); if (window.locati
// currently
init: function(aWindow) {
let self = this;
let window = XPCNativeWrapper.unwrap(aWindow);
if (window.location.href !== pageURL) {
return;
}
return {
// ...
}
}
现在window.smth在其他页面上返回XPCOM包装的nsISupports对象:(我不知道如果采用这种方法,怎么可能,但您至少可以侦听“content document global created”(内容文档全局创建)通知:并且只注入全局
observe: function(subject, topic, data) {
if (topic === 'content-document-global-created' &&
subject instanceof Ci.nsIDOMWindow) {
if (!subject.location.href.match(/http:\/\/example.com/)) {return;}
XPCNativeWrapper.unwrap(subject).myGlobal = {};
}
}
是的,这可以解决问题,但我担心内存消耗或安全问题可能会出现一些问题。我的意思是,我们可以使用nsIDOMGlobalPropertyInitializer设置哪些道具可以读取,哪些可以写入。而我们不能使用“content document global created”XPCOM事件(如果我不正确,请纠正我)。无论如何,谢谢您的回答。请尝试以下操作来代替我回答中的相应行:
Object.defineProperty(XPCNativeWrapper.unwrap(subject),'nonWritableGlobal',{writable:false,value:'myConstant'})
有关用法,请参阅。Mozilla过去使用的是\uuu defineGetter\uuuu
,如果上述方法不起作用,您也可以尝试使用,但后者已被弃用,前者应该可以。