) as a badge text in Firefox (like the " /> ) as a badge text in Firefox (like the " /> ) as a badge text in Firefox (like the "/>

how set badge text after loaded site on my extensions firefox

133 Views Asked by At

I am trying to create an extension so that I can display the number of hidden input tags (<input type="hidden">) as a badge text in Firefox (like the image ==> enter image description here)

But I have two challenges:

1- To get count <input type="hidden"> , the page must be fully loaded

2- The badge text can only be set in the background and I can not send the number of inputs to it

How do I display the number <input type="hidden"> as a badge text in Firefox when a site loads?

manifest.js

{
  "browser_specific_settings": {
    "gecko": {
      "strict_min_version": "58.0a1"
    }
  },
  "background": {
      "scripts": ["background.js"]
  },
  "browser_action": {
    "browser_style": true,
    "default_title": "test",
    "default_popup": "test.html"
  },
  "description": "test",
  "homepage_url": "https://github.com/",
  "manifest_version": 2,
  "name": "test",
  "permissions": [
    "tabs"
  ],
  "version": "1.0",

  "content_scripts": [
    {
      "matches": ["<all_urls>"],
      "js": ["test.js"]
    }
  ]
}

test.js

let HiddenInputCount = 0;
var inputs, index;

inputs = document.getElementsByTagName('input');
for (index = 0; index < inputs.length; ++index) {
    // deal with inputs[index] element.
    if(inputs[index].type == "hidden")
    {
      HiddenInputCount++;
    }
}

background.js

function updateCount() {
var HiddenInputCount = 0; //This variable must be set automatically!!!!
  browser.browserAction.setBadgeText({text: HiddenInputCount.toString()});
  if (HiddenInputCount != 0) {
    browser.browserAction.setBadgeBackgroundColor({'color': 'green'});
  } else {
    browser.browserAction.setBadgeBackgroundColor({'color': 'red'});
  }
}


updateCount();
1

There are 1 best solutions below

0
cameck On

You're on the right track, all you need to do now is leverage is runtime.sendMessage.

First add to your content script, test.js, a message:

chrome.runtime.sendMessage(hiddenInputCount)

Then setup a listener in your background.js file:

chrome.runtime.onMessage.addListener((request, sender, callback) => {
  // `request` in this example would be your hidden input value
  chrome.browserAction.setBadgeText({text: request.toString(), tabId: sender.tab.id});
  // you would probably update this to call `updateCount`
});

Note, that I'm setting the tabId value as well. This is so the badge counts are accurate for each page.