Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to check how many elements of a certain type has a page with Chrome Extension Dev

I have a simple custom Chrome Extension I've looked all over the web for this and nothing good showed up. I want to read how many elements of a certain type are in a page, through my popup.js file.

Something like this:

$('div').length

Is it possible to do this through the chrome.tabs command?

like image 741
gespinha Avatar asked Jan 30 '26 17:01

gespinha


1 Answers

  1. manifest.json:

    "permissions": [
        "tabs",
        "activeTab"
    ]
    
  2. Code:

    function countTags(tag, callback) {
        chrome.tabs.executeScript({
            code: "document.getElementsByTagName('" + tag + "').length"
        }, function(result) {
            if (chrome.runtime.lastError) {
                console.error(chrome.runtime.lastError);
            } else {
                callback(result[0]);
            }
        });
    }
    
  3. Usage:

    countTags("div", function(num) {
        console.log("Found %i divs", num);
    });
    

    getElementsByTagName(tag) can be replaced with querySelectorAll(selector) or jQuery syntax if you are sure the tab has jQuery loaded.

like image 171
wOxxOm Avatar answered Feb 01 '26 06:02

wOxxOm



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!