内容脚本中 chrome 扩展的管理权限

management permissions for chrome extension in content script

我有一个 chrome 扩展程序,它应该检查是否有另一个扩展程序,如果不是,则将 div 添加到 my-website.com 中的每个网页。所以我把它放在清单中:

"background": {
    "scripts": ["background.js"]
},

"content_scripts": [
    {
        "matches": ["http://my-website.com/*"],
        "js": ["content.js"],
        "run_at": "document_end",
        "all_frames": true
    }
],

"permissions": [
    "<all_urls>",
    "management",
    "activeTab",
    "webRequest",
    "webRequestBlocking"
]

并在我的内容脚本中添加:

chrome.management.getAll(function (apps) {
   /* Manipulate DOM */
});

但是我明白了

Uncaught TypeError: Cannot read property 'getAll' of undefined

在网页上。但是,当我打开扩展的开发工具 (chrome://extensions -> background.js) 时,我可以很好地使用 chrome.management。我如何在内容脚本上使用 chrome.management(或做类似的事情)?

可能是您的内容脚本要求后台脚本获取安装的应用程序列表。

将其放入您的内容脚本中。

 chrome.runtime.sendMessage({messageName: 'getAllApps'}, function(apps) {
// do what you want in with the apps list
});

并在您的后台脚本中监听请求和return应用程序列表

chrome.runtime.onMessage.addListener(
        function(message, sender, sendResponse) {
           if(message.messageName === 'getAllApps') {
             chrome.management.getAll(function (apps) {
                 sendResponse(apps); 
             });
           }
        }
 );

编辑

正如 post 的评论中所说,内容脚本对 chrome api See HERE 的访问权限有限,这就是为什么唯一的解决方案您将与有权访问所有内容的后台脚本进行通信。