首页 > 解决方案 > 循环读取带有 Chrome 扩展的 HTML 页面的内容

问题描述

我需要创建执行以下操作的 Google Chrome 扩展程序:

读取一组 url(可能有 2000 个 url)对于每个 url:1)我在选项卡中显示页面 2)我在新加载的页面中提取一些 html 内容 3)我用提取的内容构建了一个新 url将信息发送到我自己的本地服务,它会保存信息(我想,我只需要用这个新的 url 更新选项卡)

之后,没关系,我只是用下一个 url 再次执行相同的任务。

为了开始这项工作,我创建了以下 3 个文件。

清单.json

{
    "manifest_version": 2,
    "name": "Test",
    "description": "Test to read pages",
    "version": "1.0",
    "browser_action": {
        "default_title": "test page reader",
        "default_popup": "popup.html",
        "default_icon": "icon.png"
    },
    "permissions": [
        "activeTab"
    ]
}

popup.html 这个文件直接加载popup.js

<html>

<head>
    <script type="text/javascript" src="popup.js"></script>
</head>

<body>
    <div id="test" style="width: 100px; height: 100px; margin-top: 15px;"></div>
</body>

</html>

popup.js

urls = ["http://localhost/page1.php",
        "http://localhost/page2.php",
        "http://localhost/page3.php"
];

for (i = 0; i < urls.length; i++) { 
    myUrl = urls[i]+"&current="+i; // add "current" parameter to know where I am

    // callback function
    callbackFct = function() {
        // affecte le style de la div
        document.body.style.backgroundColor = "red";
    };

    // update tab and execute callbackFct
    chrome.tabs.update(null, {url:myUrl}, callbackFct);

}

我的代码有问题:

回调函数修改 popup.html 的背景颜色,而不是页面的背景。我该如何修改选项卡的内容而不是 popup.html 的内容?当此操作正常时,我可以替换为数据提取(步骤 2)。更新选项卡后使用回调函数的写入方式吗?目标是等到 DOM 页面完全加载。(第 3 步)调用我的服务以保存数据的最佳位置在哪里?是否在带有当前选项卡更新的回调函数中?

非常感谢您的帮助和建议。

标签: google-chrome-extension

解决方案


推荐阅读