I'm working on a small extension with the Firefox addon-sdk that has to alter the content of DOM elements in pages. I'm using PageMod to add the content script and register some events, some of which I want to pass along a callback function to, like this :
main.js
pageMod.PageMod({
include: "*",
contentScriptWhen: 'ready',
contentScriptFile: [self.data.url("my_content_script.js")],
onAttach: function(worker) {
worker.port.on("processElement", function(elementSrc, callback) {
doSomeProcessingViaJsctypes();
callback("http://someUrl/image.png");
});
}
});
my_content_script.js
var elements = document.getElementsByTagName("img");
var elementsLength = elements.length;
for (var i = 0; i < elementsLength; i++)
{
(function(obj) {
obj.setAttribute("data-processed", "true");
self.port.emit("processElement", obj.src, function(newSrc) {
console.log("replaced " + obj.src);
obj.src = newSrc;
});
})(elements[i]);
}
The error
TypeError: callback is not a function
Stack trace:
.onAttach/<@resource://gre/modules/XPIProvider.jsm -> file:///c:/users/sebast~1/appdata/local/temp/tmpjprtpo.mozrunner/extensions/jid1-gWyqTW27PXeXmA@jetpack/bootstrap.js -> resource://gre/modules/commonjs/toolkit/loader.js -> resource://jid1-gwyqtw27pxexma-at-jetpack/testextension/lib/main.js:53
I can't seem to find anything on the matter on the web. I need this approach since the processing takes a bit of time and depends on a .dll file so I can't call it from the content script.
If I were to process the element and after that call a worker.port.emit() I would have to iterate through the entire tree again to identify the element and change it's src attribute. This will take a long time and would add extra loops for each img in the document.
I've thought about generating a unique class name and appending it to the element's classes and then calling getElementsByClassName(). I have not tested this but it seems to me that it would take the same amount of time as the process I described above.
Any suggestions would be appreciated.
EDIT : I have found this answer on a different question. Wladimir Palant suggests using window-utils to get the activeBrowserWindow and then iterate thorough it's content.
He also mentions that
these low-level APIs aren't guaranteed to be stable and the window-utils module isn't even fully documented
Has anything changed since then? I was wondering if you can get the same content attribute using the tabs and if you can identify the tab from which a worker sent a self.port.emit().