I am a complete newbie in almost every programming language, so don't expect a lot from me :)
I am trying to create a Chrome extension that counts the number of times a specific string x is used on a webpage. That number is shown in a little batch on top of the extension icon (just like AdBlock shows the number of ads blocked on the page).
My code is bodged together, but this is how it currently works:
In content.js I created a script that looks for a specific string, and replaces it with exactly the same string. When replaced it adds the value 1 to a variable counter.
var elements = document.getElementsByTagName('*');
var counter = 0;
for (var i = 0; i < elements.length; i++) {
var element = elements[i];
for (var j = 0; j < element.childNodes.length; j++) {
var node = element.childNodes[j];
if (node.nodeType === 3) {
var text = node.nodeValue;
var replacedText = text.replace(/string/gi, 'string');
if (replacedText !== text) {
element.replaceChild(document.createTextNode(replacedText), node);
counter += 1;
}
}
}
}
Then in background.js I created the batch:
chrome.browserAction.setBadgeBackgroundColor({ color: [255, 0, 0, 255] });
chrome.browserAction.setBadgeText({text: counter});
But this does not seem to work.
Couple of questions:
- How do I get the value of variable 'counter' in the little batch?
- How do I make sure that the value is regenerated for every new webpage?
I created a small GitHub repo for this project, so you have access to all the files.