I created an add-on using add-on builder. I attached a content-script to the pageMod in main.js
My content script counts the number of dynamic tags created using document.createElement(). This is done by creating a hook to document.createElement() and added this function to webpage by creating a script tag. My code is as follows.
contentscriptFile:
addJS_Node ("var count=0;");
function LogDocCreateElement ()
{
var oldDocumentCreateElement = document.createElement;
document.createElement = function(tagName)
{
var elem = oldDocumentCreateElement.apply (document, arguments);
console.log("Dynamically created a(n)", tagName);
count++;
return elem;
}
}
addJS_Node (null, null, LogDocCreateElement);
function addJS_Node (text, s_URL, funcToRun) {
var D = document;
var scriptNode = D.createElement ('script');
scriptNode.type = "text/javascript";
if (text) scriptNode.textContent = text;
if (s_URL) scriptNode.src = s_URL;
if (funcToRun) scriptNode.textContent = '(' + funcToRun.toString() + ')()';
var targ = D.getElementsByTagName ('head')[0] || D.body || D.documentElement;
targ.appendChild (scriptNode);
}
window.addEventListener("load", function() {alert(count) }, false);
Now I am getting uncaught exception: ReferenceError: count is not defined.
How can I access this count variable?
Please see the documentation on how content scripts access web pages – they don’t see any custom properties and methods that the web page added to the DOM. In your case you would need to access the
countvariable viaunsafeWindowobject:However, as the documentation notes you should avoid using
unsafeWindowif somehow possible. Here the obvious course of action would be to avoid creating thecountvariable in the page altogether. So instead of this:You would just declare the variable:
But you would need to replace
unsafeWindow.document.createElementrather thandocument.createElementin order for this change to be visible to the web page. AvoidingunsafeWindowhere will be way more complicated, maybe you can use mutation events instead?