How to access a variable attached to the webpage using contentscript in - contentscript using Add-on builder
-
05-06-2021 - |
سؤال
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 count
variable via unsafeWindow
object:
unsafeWindow.count++;
However, as the documentation notes you should avoid using unsafeWindow
if somehow possible. Here the obvious course of action would be to avoid creating the count
variable in the page altogether. So instead of this:
addJS_Node ("var count=0;");
You would just declare the variable:
var count = 0;
But you would need to replace unsafeWindow.document.createElement
rather than document.createElement
in order for this change to be visible to the web page. Avoiding unsafeWindow
here will be way more complicated, maybe you can use mutation events instead?