chrome.webRequest.onBeforeRequest.addListener 无法读取未定义的 属性 'onBeforeRequest'

chrome.webRequest.onBeforeRequest.addListener Cannot read property 'onBeforeRequest' of undefined

我正在尝试构建自己的 chrome 扩展程序,并且正在尝试使用 onBeforeRequest 添加事件处理程序。

我的manifest.json:

{
    "manifest_version": 2,

    "name": "My extension",
    "description": "some descrpition",
    "version": "1.0",
    "permissions": [
        "activeTab",
        "tabs",
        "webRequest",
        "webNavigation",
        "management",
        "http://*/*",
        "https://*/*"
    ],
    "background": {
        "scripts": [
            "js/jquery-2.1.4.min.js",
            "js/background.js"
        ],
        "persistent": true
     },
    "browser_action": {
        "default_icon": "imgs/img.png",
        "default_title": "extension"
    },
    "icons" : {
      "64" : "imgs/vergrootglas.png"  
    }
}

我的background.js:

function callback(param1,param2,param3){
    alert(param1);
    alert(param2);
    alert(param3);
}
//alert("test");



chrome.webRequest.onBeforeRequest.addListener(callback);

我已将此加载到我的 chrome 中。但是每次我在控制台中收到此消息时:

Uncaught TypeError: Cannot read property 'onBeforeRequest' of undefined

我不知道我做错了什么,我发现了这个: https://developer.chrome.com/extensions/webRequest

但是代码的例子好像和我做的差不多。 我在这里错过了什么?

上面的评论对我来说没有意义。上面有一个后台脚本,它似乎有适当的权限...一些可能有帮助的额外评论...

您需要在清单文件中添加一个后台页面,并在清单文件中添加适当的权限,以便后台页面可以访问 webRequest API。看这个例子:chrome.webRequest not working?

如 Mihai 所述,如果您需要让内容脚本执行操作,请查看此页面:https://developer.chrome.com/extensions/messaging

将此添加到您的内容脚本中(您可以将问候语更改为操作,将问候更改为后台脚本应执行的操作):

chrome.runtime.sendMessage({greeting: "hello"}, function(response) {
   console.log(response.farewell);
});

将此添加到您的后台页面(您可以执行 if 语句并根据消息执行不同的操作):

chrome.runtime.onMessage.addListener(
  function(request, sender, sendResponse) {
    console.log(sender.tab ?
                "from a content script:" + sender.tab.url :
                "from the extension");
    if (request.greeting == "hello")
      sendResponse({farewell: "goodbye"});
  });

我刚刚 运行 遇到了类似的问题,只是我遇到的问题与权限无关,实际上是 Webpack 问题。

我的背景脚本意外地与我的内容脚本捆绑在一起。后台 js 正在导出内容脚本正在使用的某些常量,导致仅限于后台文件(例如 chrome.webRequest)的方法作为内容脚本的一部分被调用,因此无法读取未定义的 属性...