Search code examples
javascriptdebugginggoogle-chrome-extensionhttprequesthttpwebrequest

Chrome extension that prevents parts of a page from being loaded


I'm working on a Chrome extension that simplifies the homepage of YouTube by removing the recommended videos on the homepage. The video thumbnails take a significant time to load, so I want to find a way to cancel those requests. So far, I have the following

manifest.json includes

"background": { 
  "persistent": true, 
  "scripts": ["background.js"] 
},
"permissions": [
  "webRequest", 
  "webRequestBlocking", 
  "*://www.youtube.com/"
]

background.js

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

Now, I believe I just need to find which paths to cancel. I've console logged a few but am getting pretty lost in understanding what each request does. Some requests I cancel result in nothing being loaded while others result in the header being loaded but not clickable. I've tried looking at network activity with inspector but don't have much experience using that tool. What's a good approach to this problem?


Solution

  • In devtools element inspector you can examine a thumbnail to see its URL, then reload the page with network inspector open and see similar URLs:

    • https://i.ytimg.com/vi/* - thumbnails
    • https://yt*.ggpht.com/* - user avatars

    * is a placeholder for the varying part.

    To be able to block these URLs you need to add them to manifest.json:

    "permissions": [
      "webRequest", 
      "webRequestBlocking", 
      "*://www.youtube.com/",
      "https://i.ytimg.com/vi/*",
      "https://yt*.ggpht.com/*"
    ]
    

    Since you want to block only images it would make sense to register the listener only for this type of requests so it doesn't execute needlessly, same for the URL patterns. To avoid spamming the console with messages about network requests being blocked you can redirect to a dummy data URI.

    chrome.webRequest.onBeforeRequest.addListener(
      info => info.initiator === 'https://www.youtube.com' && { redirectUrl: 'data:,' },
      {
        urls: [
          'https://i.ytimg.com/vi/*',
          'https://yt*.ggpht.com/*',
        ],
        types: [
          'image',
        ],
      },
      ['blocking']
    );