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
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.
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):
chrome.runtime.sendMessage({greeting: "hello"}, function(response) {
console.log(response.farewell);
});
Add this to your background page (you can do if statements and peform different actions based on the message):
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"});
});