chrome.webRequest.onBeforeRequest causes some features of web pages to fail to load

1.6k Views Asked by At

I'm writing a chrome extension. I want it to block all pages on en.wikipedia.org, EXCEPT the Main_Page. I used chrome.webRequest.onBeforeRequest to do this.

Here is the code I used for the background script of my chrome extension:

chrome.webRequest.onBeforeRequest.addListener(
  function(details) {
    if (details.url=="https://en.wikipedia.org/wiki/Main_Page") {
      return {cancel: false};
    } else {
      return {cancel: true};
    }
  },
  {urls: ["https://en.wikipedia.org/*"]},
  ["blocking"]);

This code correctly blocks all Wikipedia pages except Main_Page.

It does display the Main_Page, but it shows a simplified version without CSS.

I have tried this with other websites (i.e. block "https://www.reddit.com/*" except for exactly "https://www.reddit.com/"), and in these other cases some page elements fail to load.

Why does this happen? Can I use chrome.webRequest.onBeforeRequest and have the web pages display correctly?

2

There are 2 best solutions below

3
wOxxOm On BEST ANSWER

If the site is using subpaths for its resources, not a separate subdomain, your URL pattern will nuke every such resource such as Wikipedia's CSS.

Simply block the top URL by specifying types filter:

chrome.webRequest.onBeforeRequest.addListener(
  info => ({
    cancel: !info.url.startsWith('https://en.wikipedia.org/wiki/Main_Page'),
  }),
  {
    urls: ['https://en.wikipedia.org/*'],
    types: ['main_frame', 'sub_frame'],
  },
  ['blocking']
);
0
Mebin Joe On

The following example illustrates how to block all requests to www.abc.com:

  chrome.webRequest.onBeforeRequest.addListener(
    function(details) {
      return {cancel: details.url.indexOf("://www.abc.com/") != -1};
    },
    {urls: ["<all_urls>"]},
    ["blocking"]);

As this function uses a blocking event handler, it requires the "webRequest" as well as the "webRequestBlocking" permission in the manifest file.

The following example achieves the same goal in a more efficient way because requests that are not targeted to www.abc.com do not need to be passed to the extension:

 chrome.webRequest.onBeforeRequest.addListener(
    function(details) { return {cancel: true}; },
    {urls: ["*://www.abc.com/*"]},
    ["blocking"]);

More details: https://developer.chrome.com/extensions/webRequest