首页 > 解决方案 > 如何在 chrome 扩展中添加“读取和更改您访问的网站上的所有数据”权限?

问题描述

我需要Read and change all your data on the websites you visit在我的 chrome 扩展中添加此权限,以便我可以读取DOM页面的元素。

清单.json

{
    "name": "BBox Counter",
    "version": "2.0",
    "manifest_version": 2,
    "content_scripts": [
        {
            "match_about_blank": true,
            "matches": ["<all_urls>"],
            "js": ["content.js"]
        }
    ],
    "browser_action": {
        "default_icon": "16.png",
        "default_popup": "popup.html",
        "default_title": "BBox Counter"
    },
    "permissions": [
      "activeTab",
      "contextMenus",
      "storage"
    ],
    "content_security_policy":"script-src 'self' https://www.gstatic.com/ https://*.firebaseio.com https://www.googleapis.com; object-src 'self'",
    "background": {
        "page": "background.html"
    }
}

更新 content.js

console.log("context started...");

chrome.runtime.onMessage.addListener(gotMessage);

function gotMessage(message, sender, sendResponse) {
    console.log("Message received");
    const element_id = "event-capturer";

    if (message == 'count') {
        if (document.getElementById(element_id)) {
            const cnt = document.getElementById(element_id).getElementsByTagName("rect").length;
            alert("Count is: "+cnt);
        } else {
            alert("No element with '"+element_id+"' tag.");
        }
    }
}

该网站有一个div带有 idevent-capturer但我不知道为什么它会成为其他部分"No element with '"+element_id+"' tag."

请帮帮我。谢谢

标签: javascriptgoogle-chrome-extensionextension-methods

解决方案


你做对了。

当您像现在所做的那样注入内容脚本时,您将获得正确的权限。

   "content_scripts": [
        {
            "match_about_blank": true,
            "matches": ["<all_urls>"],
            "js": ["content.js"]
        }
    ]

这意味着您注入content.js到每个网页。尝试在 content.js 中编写一些代码alert("I'm here"),然后重新加载扩展,然后打开任何页面,您都会收到警报。

如何查看权限状态?

  • 右键单击工具栏中的扩展图标
  • 悬停在this can read and change site date
  • 如果它on all sites默认选择了,那么它可以访问所有站点。

推荐阅读