CHROME WebRequest APIs示例错误:“onBeforeRequest”仅可在扩展进程中使用。

5

我尝试测试WebRequest APIs的一个示例,但是出现了错误:

"onBeforeRequest"只能在扩展进程中使用。 manifest.json:

{
    "name": "example",
   "version": "1.0",
  "permissions": [
    "experimental",
    "http://*/*", "https://*/*"
  ],
    "content_scripts": [ {
      "js": [ "foo.js" ],
      "matches": [ "http://*/*", "https://*/*" ],
      "run_at": "document_start"
   } ]
}

foo.js 就是示例1。

2个回答

14

Chrome扩展程序功能(包括webRequest API)无法在内容脚本(如您示例中的foo.js)中使用。如果您希望从内容脚本中使用webRequest,则可以使用消息传递功能与扩展程序的后台页面进行通信。后台页面可以直接使用webRequest并将响应(如果有的话)传回内容脚本。


谢谢。我有点太急于尝试那些API了...甚至没有仔细阅读文档...现在它按预期工作了。 - Huang
1
@Huang,Chrome的文档团队需要向PHP文档学习,后者采用真正适合教程的风格编写。 - Pacerier

3
您需要在清单文件中添加一个背景页和适当的权限,以便背景页可以访问webRequest API。请参考此示例: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"});
  });

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