Incremental counter Chrome extension batch (Javascript)

Viewed 285

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:

  1. How do I get the value of variable 'counter' in the little batch?
  2. 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.

1 Answers

1: Use chrome messaging API to pass your counter value to the background page and on the background when you receive the value, update the badge value with the counter. see https://developer.chrome.com/extensions/messaging

2: Content Scripts are always re-executed on page load since your counter variable in content.js is not stored in memory, so your counter variable will always reset on page load.

Solution

content.js

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;
            }
        }
    }
}

chrome.runtime.sendMessage({counter: counter});

background.js

chrome.browserAction.setBadgeBackgroundColor({ color: [255, 0, 0, 255] });

chrome.runtime.onMessage.addListener(function(request, sender, sendResponse) {
    chrome.browserAction.setBadgeText({text: `${request.counter}`});
});
Related