如何共享内容脚本和插件之间的代码? [英] How to share code between content script and addon?
问题描述
我在一个名为 utils.js
的文件中有一些代码,我想从addon main.js
和 page-mod
的内容脚本。
是否可以同时引用 utils.js
?如果是这样的话,怎么样?
编辑:更好的办法是让我可以在谷歌浏览器扩展中使用相同的代码。 b
我遇到了同样的问题。你会认为会有一个明显的解决方案。这里是我一直在做的firefox(没有与铬工作):
我有一个文件lib / dbg.js包含我的基本调试功能,我想到处使用。
在我的main.js中的每个可编写脚本的模块中,我都有这个:
$ $ $ ($ {
...
contentScript:export_internals(require('dbg')),
contentScriptFile:my-actual-scripts.js
...
然后在主函数中我有一个函数
function export_internals(module){
var code ='';
for(name in module){
var val = module [name];
if(val.constructor === String)
code + = name +'='+ val +';';
else
code + = val;
}
返回码;
}
基本上只是循环通过导出的属性(变量,函数等),并利用的东西像Function.toString()基本上构建了一个字符串版本的DBG模块,并将其作为内联内容脚本传递。这个函数可能不是非常通用的,因为我只是写它来处理简单的函数和字符串(我只需要两种数据类型),但是即使你只是做一些类似的事情,也应该很容易地应用原理。
$ b
contentScript:require('dbg')。my_function.toString()
到目前为止,这显然是一个黑客,但一个相当可靠的。那是你在找什么?
I'm writing an extension for Firefox 4+.
I have some code in a file named utils.js
which I'd like to call from both the addon's main.js
and from the page-mod
's content script.
Is it possible to refer from both to the same utils.js
? If so, how?
Edit: Even better would be a solution allowing me to use the same code in a Google Chrome extension, too.
I've run into this same problem. You'd think there'd be an obvious solution. Here's what I've been doing for firefox (haven't worked with chrome):
I have a file lib/dbg.js containing my basic debug functions that I want to use everywhere.
In each content scriptable module in my main.js, I have this:
contextMenu.Item({
...
contentScript: export_internals(require('dbg')),
contentScriptFile: my-actual-scripts.js
...
and then in main I have a function
function export_internals(module) {
var code = '';
for (name in module) {
var val = module[name];
if (val.constructor === String)
code += name + ' = "' + val + '";';
else
code += val;
}
return code;
}
which basically just cycles through the exported properties (variables, functions, etc) and makes use of things like Function.toString() to basically build a stringified version of the dbg module and pass it as an inline content script. This function probably isn't hugely general as I just wrote it to handle simple functions and strings (the only two data types I needed) but the principle should be easily applied even if you were to just do something like
contentScript: require('dbg').my_function.toString()
It's clearly a bit of a hack but a pretty reliable one so far. Is that what you were looking for?
这篇关于如何共享内容脚本和插件之间的代码?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!