Search code examples
javascriptgoogle-chrome-extensionchrome-webrequest

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


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?


Solution

  • 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']
    );