如何创建 chrome(扩展名)webRequest 侦听器?

How to create a chrome (extension) webRequest listener?

我正在尝试创建一个 chrome (extension) webRequest listener。但是,无论我尝试什么,我都无法访问 chrome.webRequest 对象 - 我的程序因 Uncaught TypeError: Cannot read property 'onCompleted' of undefined 而崩溃。同样在命令行调试显示 chrome.webRequest 不存在。

我怀疑我在权限方面做错了什么,因为我没有看到许多其他 Whosebug 问题或 chrome 具有相同问题的错误报告。

这是我的manifest.json

{
    "manifest_version": 2,

    "name": "my extension",
    "description": "my extension description",
    "version": "1.0",

    "permissions": [
        "activeTab",
        "webRequest",
        "webRequestBlocking",
        "https://<myextension>.com/*",
    ],

    "page_action": {
        "default_icon": {                    // optional
            "19": "myextension.png",           // optional
            "38": "myextension.png"            // optional
        }
    },

    "content_scripts": [
        {
            "matches": ["https://<myextension>.com/*"],
            "css": ["myextension.css"],
            "js": ["jquery.js", "myextension.js"]
        }
    ]
}

这是我的myextension.js

var myfilter = {
    urls: ['https://myextension.com/*']
}

function mycallback(){
    console.log('received request response');
}

chrome.webRequest.onCompleted.addListener(mycallback, myfilter);

知道我可能做错了什么吗? 我是 运行 OSX 10.10.2chrome 40.0.2214.94.

大部分ChromeAPI不能在Content Scripts中使用,包括webRequest:

However, content scripts have some limitations. They cannot:

Use chrome.* APIs, with the exception of:

  • extension ( getURL , inIncognitoContext , lastError , onRequest , sendRequest )
  • i18n
  • runtime ( connect , getManifest , getURL , id , onConnect , onMessage , sendMessage )
  • storage

您需要在后台页面中处理此事件并使用 Messaging 与上下文脚本通信。