Search code examples
javascriptgoogle-chromegoogle-chrome-extensionadblock

Intercept URLs based on patterns with Chrome extension


Scenario:

  • filter some redirect URLs based on patterns
  • Show a message stating that a URL was blocked due to a redirect
  • "unblock" a request in the same tab if a previous request was blocked

My list of URL patterns to use in webRequest.onBeforeRequest contains bit.ly. Then I hit the URL bit.ly/2qlHCT which redirects to google.com. In this case, I'll show a message like "request was blocked", but I don't want to actually block the request by returning { cancel: true } in onBeforeRequest's callback.

If the user tries to normally access google.com in the same tab, then I'll show a message "nothing was blocked". So, this is similar what Adblock does when you add filters for a specific domain. Adblock's icon goes green if the domain is allowed, otherwise it turns red.

I know that I can use chrome.storage to save information about a blocked request, but how can I achieve that when a URL pattern doesn't match?


Solution

  • The solution was really straightforward. I was using chrome.tabs.query to block tabs, but it's an async method and I needed a sync response. Using localStorage did the trick.

    function blockRequest(tabId) {
      let tabs = localStorage.blocked_tabs;
      tabs = (tabs !== undefined) ? JSON.parse(tabs) : [];
      tabs = tabs.filter(function (item) {
        return item !== tabId;
      });
      localStorage.setItem('blocked_tabs', JSON.stringify(tabs));
    }
    

    Then, I just added the function blockRequest as listener to chrome.webRequest.onBeforeRequest and some filters.

    chrome.webRequest.onBeforeRequest.addListener(blockRequest, { urls: filters, types: ['main_frame'] });