Chrome extension declarativeNetRequest: get notified on request blocked

794 views Asked by At

The new manifest version 3 of Chrome extension API offers a new function setExtensionActionOptions which allows a typical content blocker to display the number of blocked HTTP requests for a particular tab. The question is: when to call this API? How do I get notified that a request was just blocked and I need to call it with "increment: 1"? I'm looking for the event "onRequestBlocked" or some workaround.

The alarm API is no good because it fires once per minute. Ideally, I'd like to have this number updated in real time, as it is possible with the old MV2.

Another potential solution is to keep the service worker always running which kind of defeats the fruit of moving to MV3 at all.

2

There are 2 answers

1
wOxxOm On

There's no way to get notification outside of debugging in unpacked mode via onRuleMatchedDebug event.

You can enable automatic display of the number of the blocked requests on the icon badge.
For example, do it when the extension is installed/updated:

chrome.runtime.onInstalled.addListener(() => {
  chrome.declarativeNetRequest.setExtensionActionOptions({
    displayActionCountAsBadgeText: true,
  });
});

You can also provide an explicit increment using tabUpdate property at any time you want:

chrome.runtime.onMessage.addListener((msg, sender, sendResponse) => {
  if (msg.type === 'block') {
    chrome.declarativeNetRequest.setExtensionActionOptions({
      tabUpdate: {
        tabId: sender.tab.id,
        increment: msg.count, // Negative values will decrement the count
      },
    });
  }
});
0
Serhii On

For future seekers: I've been able to find the following solution

chrome.webRequest.onErrorOccurred.addListener(
   (details) => {
      chrome.declarativeNetRequest.setExtensionActionOptions({
         tabUpdate: {
            tabId: details.tabId,
            increment: 0
         }
      });
   },
   {
      urls: ["<all_urls>"]
   }
);

Yes, this also counts requests that are blocked by other extensions, but in practice I believe this is not so much of a problem. Another thing that's hard for me to explain, is this increment: 0 parameter. For some reason, the action count is actually incremented by increment + 1, not increment when the tabUpdate argument is provided. So, bizarre enough but works for me quite well this far.