我正在尝试为Firefox编写一个扩展,允许我从网页访问它的内部函数/类/对象。我希望它们在DOM中是可见和可访问的。当扩展作为组件从chrome.manifest文件加载时,它就工作了,但在e10s(多进程Firefox(中似乎已经不可能了
所以我一直在尝试,到目前为止我找到的最好的选择似乎是使用exportFunction、createObjectIn和cloneInto函数。当期望使对象从扩展本身加载的页面中可见而不是从远程页面中可见时,它们可以正常工作
我现在正在使用Addon SDK,我的代码是
然后
function injectTest(event) {
let domWindow = event.subject;
//This creates and object that is always visible but never accesible from page not loaded by the extension
foo = Cu.createObjectIn(domWindow.wrappedJSObject, {defineAs: "testSDK"});
//This exports my function fine but I can export it only into an existing object
//That's why I'm using "crypto" here
Cu.exportFunction(test.bind(this, domWindow),
domWindow.crypto.wrappedJSObject,
{ defineAs: "test" });
//This exports my function to my object but only on pages loaded by the extension
Cu.exportFunction(test.bind(this, domWindow),
foo,
{ defineAs: "test2" });
//Same here, cloned_var seems to be not accesible from remote webpage
var to_be_cloned = {"greet" : "hey"};
foo.cloned_var = Cu.cloneInto(to_be_cloned, foo);
}
exports.main = function(options, callbacks) {
if (!gInitialized &&
(options.loadReason == "startup" ||
options.loadReason == "install" ||
options.loadReason == "enable")) {
log("initializing - " + options.loadReason);
try {
events.on("content-document-global-created", injectTest);
} catch (error) {
log(error);
}
gInitialized = true;
}
};
我对javascript和Firefox扩展完全陌生,所以我不知道如何让它工作。我做错了什么?有什么更好的方法可以访问扩展的对象吗?
提前感谢您的帮助。
@编辑19.05.15尝试使用页面模式。它确实有效,但没有我需要的那么好。main.js文件
var data = require("sdk/self").data;
var pageMod = require("sdk/page-mod");
pageMod.PageMod({
include: "mywebsite",
contentScriptFile: [data.url("cscript.js")],
contentScript: 'window.alert("Page matches ruleset");'
});
cscript.js文件(在数据文件夹中(
var contentScriptObject = {
"greeting" : "hello from add-on",
b: 1,
powitaj: function(){
return(this.greeting);
}, //when called from console returns "hello from add-on"
is_b: function(){
if(b){
return true;
}else{
return false;
}
}, //undefined
is_thisb: function(){
if(this.b){
return true;
}else{
return false;
}
}, //returns 1
func: function(){
console.log("ok")
}, //returns "ok"
is_func: function(){
func();
}, //undefined
is_thisfunc:function(){
this.func();
} //undefined
};
因此,在我的网站上,我可以访问内部变量(实际上也是全局定义的变量,并对其进行修改(,我也可以访问内部函数(不是外部函数-不包括在代码中(,但我的内部函数不能相互调用,我希望能够做到这一点。
要在e10s内容进程中运行chrome特权代码,您需要框架脚本
SDK有一些包装模块,以简化父进程和子进程之间的通信和模块加载
如果你只需要exportFunction
/cloneInto
/createObjectIn
,那么使用页面模块可能就足够了,如果我记得正确的话,这些助手在它的上下文中是可用的。