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

I have a regular Chrome extension that I've looked all over the internet and nothing good has come up. I want to read how many elements of a particular type are on a page through my popup.js

file.

Something like that:

$('div').length

      

Is it possible to do this with a command chrome.tabs

?

+3


source to share


1 answer


  • manifest.json

    :

    "permissions": [
        "tabs",
        "activeTab"
    ]
    
          

  • 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]);
            }
        });
    }
    
          

  • Application:

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

    getElementsByTagName(tag)

    can be replaced with syntax querySelectorAll(selector)

    or jQuery if you are sure the tab is loaded with jQuery.



+2


source







All Articles