CHROME WebRequest API 示例错误:“onBeforeRequest”只能在扩展过程中使用
我尝试测试 WebRequest
的示例API,但抛出错误:
“onBeforeRequest”只能在扩展进程中使用。 清单.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
I try to test a example of WebRequest
APIs, but throw error:
"onBeforeRequest" can only be used in extension processes.
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
is exactly the example 1
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
Chrome 扩展函数(包括 webRequest API)不能在内容脚本中使用(示例中为
foo.js
)。如果您希望从内容脚本使用 webRequest,则可以使用 消息传递功能,用于与扩展程序的 背景页面。后台页面可以直接使用 webRequest 并将响应(如果有)转发回内容脚本。Chrome extension functions (which includes the webRequest API) cannot be used in content scripts (
foo.js
in your example). If you wish to use webRequest from a content script, you can use the messaging functionality to talk to the extension's background page. The background page can use webRequest directly and relay the response (if any) back to the content script.您需要在清单文件中添加后台页面,并在清单文件中添加适当的权限,以便后台页面可以访问 webRequest API。请参阅此示例: chrome.webRequest 不起作用?
正如 Mihai 提到的,如果您需要内容脚本执行操作,请查看此页面: https://developer.chrome.com/extensions/messaging
将其添加到您的内容脚本中(您可以将问候语更改为操作,并将 hello 更改为后台脚本应执行的操作):
将此添加到您的背景中页面(您可以执行 if 语句并根据消息执行不同的操作):
You need to add a background page in the manifest file and the appropriate permissions in the manifest so the background page can access the webRequest APIs. See this example: chrome.webRequest not working?
As Mihai mentioned, if you need to have the content script perform the action, check this page out: https://developer.chrome.com/extensions/messaging
Add this to your content script (you can change greeting to action and hello to which action the background script should perform):
Add this to your background page (you can do if statements and peform different actions based on the message):