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

14

我正在尝试构建自己的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

但是代码示例似乎与我做的相同。我漏掉了什么?


据我所知,在内容脚本中无法执行该操作。 - Jaromanda X
使用Chrome扩展API提供的任何手段,在扩展脚本和内容脚本之间进行通信(我只知道Firefox插件,抱歉,它们使用?.port.emit?.port.on,其中?是self或其他一些东西 - 不确定Chrome是否以同样的方式工作)。 - Jaromanda X
1
@FIA2008,这个没有意义。你能否上传扩展并在评论中提供链接?还请使用 console.log 而不是 alert - wOxxOm
请更新问题的其余部分,而不仅仅是代码。您所描述的错误已经不适用了。如果您进行编辑,我可以回答您的问题。 - Xan
显示剩余4条评论
2个回答

2

对我来说,上面的评论没有意义。有一个背景脚本在上面,它似乎拥有适当的权限... 一些额外的注释可能有所帮助...

您需要在清单文件中添加一个背景页面和相应的权限,以便背景页面可以访问webRequestAPIs。请参阅此示例:chrome.webRequest not working?

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

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

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"});
  });

1
我刚遇到了类似的问题,但是对我来说问题与权限无关,实际上是一个Webpack问题。
我的背景脚本意外地与我的内容脚本捆绑在一起。背景js导出了某些常量,内容脚本正在使用它们,导致被限制在背景文件中的方法(如chrome.webRequest)作为内容脚本的一部分被调用,因此出现了“无法读取未定义的属性”...

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接