Search code examples
javascriptcookiesgoogle-chrome-extensioncross-browserfirefox-addon

How to manipulate webRequest cookie in a cross-browser extension?


I am trying to edit cookie for all API calls using webRequest from a cross-browser (supporting chrome and Firefox) extension which I am creating.

Following is the code:

chrome.webRequest.onBeforeSendHeaders.addListener(
 data => { /* cookie manipulation logic */ },
 { urls: ['https://*/*'] },
 ['blocking', 'requestHeaders', 'extraHeaders']
);

Problem: In Chrome, the code works with extraHeaders and in Firefox the same code works only if extraHeaders is removed. How can I make it work on both browsers?

Following is the browser doc reference for Chrome and Firefox.

Chrome: Chrome documentation states that extraHeaders is needed if we want to manipulate cookie. Reference picture below. Reference link: Link

enter image description here

Firefox:

Firefox documentation doesn't tell to use any extra spec to manipulate cookie. Instead it gives error when extraHeaders is present in the third argument of addListener.


Solution

  • The API exposes all predefined constants in chrome.webRequest.OnXXXXXXXXX objects for each event so only in new Chrome such objects will have EXTRA_HEADERS key with extraHeaders value whereas in Firefox and old Chrome it'll be undefined, which can be filtered out via filter():

    chrome.webRequest.onBeforeSendHeaders.addListener(
      listenerFunc,
      { urls: ['*://*/*'] },
      ['blocking', 'requestHeaders', 
       chrome.webRequest.OnBeforeSendHeadersOptions.EXTRA_HEADERS].filter(Boolean)
    );