google-chrome-extensionchrome-extension-manifest-v3chrome-declarativenetrequest

Session rule to match all requests coming from iframes


I had an extension which was using the parentFrameId property on onHeadersReceived with the webRequestBlocking permission to strip specific headers for all the requests coming from the iframes of a tab.

To achieve this, the condition was: request.tabId === tabId && request.parentFrameId !== -1.

// Tab ID to instrument.
const tabId = 42

chrome.webRequest.onHeadersReceived.addListener((details) => {
  if (details.responseHeaders && details.tabId === tabId && details.parentFrameId !== -1) {
    return {
      responseHeaders: details.responseHeaders.filter( /* filter */ ),
    }
  }
}, {tabId, urls: ['*://*/*']}, [
  'blocking',
  'responseHeaders',
  'extraHeaders',
])

But with the new declarativeNetRequest API, I can't find a good RuleCondition to mimic this behavior.

I tried this:

// Tab ID to instrument.
const tabId = 42

await chrome.declarativeNetRequest.updateSessionRules({
  addRules: [
    {
      id: 1,
      action: {
        responseHeaders: [
          {
            header: 'my-header',
            operation: chrome.declarativeNetRequest.HeaderOperation.REMOVE,
          },
        ],
        type: chrome.declarativeNetRequest.RuleActionType.MODIFY_HEADERS,
      },
      condition: {
        resourceTypes: [chrome.declarativeNetRequest.ResourceType.SUB_FRAME],
        tabIds: [tabId],
      },
    },
  ],
})

But as said in the comments of this StackOverflow question, "sub_frame means the request that creates the iframe itself, not its own requests".

Do you see any condition that could mimic parentFrameId !== -1 with the declarativeNetRequest API?


Solution

  • I found a workaround: use a combination of the non-blocking webRequest API and the declarativeNetRequest API.

    I won't add a snippet, but here's the idea:

    This way, I can achieve a behavior close enough to parentFrameId.