【问题标题】:CHROME WebRequest APIs example error: "onBeforeRequest" can only be used in extension processesCHROME WebRequest APIs 示例错误:“onBeforeRequest”只能在扩展进程中使用
【发布时间】:2011-11-22 07:12:42
【问题描述】:

我尝试测试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

【问题讨论】:

    标签: google-chrome-extension webrequest


    【解决方案1】:

    Chrome 扩展功能(包括 webRequest API)不能在内容脚本中使用(在您的示例中为foo.js)。如果您希望使用内容脚本中的 webRequest,您可以使用 messaging 功能与扩展程序的 background page 对话。后台页面可以直接使用 webRequest 并将响应(如果有)转发回内容脚本。

    【讨论】:

    • 谢谢。我尝试这些 API 有点太快了……甚至没有通读文档……现在它可以按预期工作了。
    • @Huang,Chrome 的文档团队需要学习以真正正确的教程风格编写的 PHP 文档。
    【解决方案2】:

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

    正如米海所说,如果您需要让内容脚本执行操作,请查看此页面: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"});
      });
    

    【讨论】:

      猜你喜欢
      • 2021-12-15
      • 2016-09-30
      • 2017-01-25
      • 2015-03-19
      • 1970-01-01
      • 1970-01-01
      • 2019-01-08
      • 2012-08-13
      相关资源
      最近更新 更多