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

The*_*uls 5 javascript jquery google-chrome webrequest google-chrome-extension

我正在尝试构建自己的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"  
    }
}
Run Code Online (Sandbox Code Playgroud)

我的background.js:

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



chrome.webRequest.onBeforeRequest.addListener(callback);
Run Code Online (Sandbox Code Playgroud)

我把它加载到了我的chrome中.但每次我在控制台中收到此消息时:

未捕获的TypeError:无法读取未定义的属性'onBeforeRequest'

我无法弄清楚我错了什么,我发现了这个:https: //developer.chrome.com/extensions/webRequest

但代码的例子似乎和我的做法完全一样.我在这里错过了什么?

Sco*_*Izu 2

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

您需要在清单文件中添加后台页面,并在清单文件中添加适当的权限,以便后台页面可以访问 webRequest API。请参阅此示例:chrome.webRequest 不起作用?

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

将其添加到您的内容脚本中(您可以将greeting更改为action,并将hello更改为后台脚本应执行的操作):

chrome.runtime.sendMessage({greeting: "hello"}, function(response) {
   console.log(response.farewell);
});
Run Code Online (Sandbox Code Playgroud)

将其添加到您的背景页面(您可以执行 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"});
  });
Run Code Online (Sandbox Code Playgroud)