Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
99 views
in Technique[技术] by (71.8m points)

javascript - 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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)
  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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...