如何检查具有Chrome Extension Dev 的页面有多少特定类型的元素

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

我有一个简单的自定义 Chrome 扩展程序 我为此在整个网络上进行了搜索,但没有找到任何好的结果。我想通过我的 popup.js 文件读取页面中有多少特定类型的元素。

像这样:

$('div').length

是否可以通过 chrome.tabs 命令执行此操作?

  1. manifest.json:

    "permissions": [
        "tabs",
        "activeTab"
    ]
    
  2. 代码:

    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. 用法:

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

    getElementsByTagName(tag) 可以替换为 querySelectorAll(selector) 或 jQuery 语法,如果您确定选项卡已加载 jQuery。