5

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

Mateen Ulhaq
  • 24,552
  • 19
  • 101
  • 135
Huang
  • 1,919
  • 3
  • 15
  • 11

2 Answers2

14

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.

Mihai Parparita
  • 4,236
  • 1
  • 23
  • 30
  • Thank you. I am a little too fast to try those API... not even read through the document... now it works as expect. – Huang Nov 23 '11 at 08:10
  • 1
    @Huang, Chrome's documentation team need to learn from the PHP documentations which are written in real proper tutorial style. – Pacerier Aug 05 '16 at 04:11
3

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"});
  });
Community
  • 1
  • 1
Scott Izu
  • 2,229
  • 25
  • 12