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?
My solution was to
The solution has lead to a better design of my addon. But I don't know if the async approach would work in your situation.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With