Can Some Body Finally say what is the official way to pass cookie from the content scripts to service-worker

39 views
Skip to first unread message

shubham kudekar

unread,
Jun 28, 2024, 8:49:06 AM (2 days ago) Jun 28
to Chromium Extensions
I have a extension , i am injecting that  in the dom of a website inside an i frame ,


i need to call an api which is being called in the service worker ,

but i want to pass all the available cookies from content script to service worker , so that they are availaible while making the api call.

Can SomeBody Help here

woxxom

unread,
Jun 28, 2024, 10:32:41 AM (2 days ago) Jun 28
to Chromium Extensions, shubham kudekar
For the main page (not an iframe) it should happen automatically as the extension already has a host permission for this site. For sites inside an iframe there's a problem with cookie partitioning I guess, in which case you may need to send document.cookie to your background script, which will use declarativeNetRequest

chrome.runtime.onMessage.addListener((msg, sender, sendResponse) => {
  makeRequest(msg).then(sendResponse);
  return true;
});
async function makeRequest({url, opts, cookie}) {
  const old = await chrome.declarativeNetRequest.getSessionRules();
  const id = old.length + 1;
  await chrome.declarativeNetRequest.updateSessionRules({
    addRules: [{
      id,
      condition: {
        initiatorDomains: [chrome.runtime.id],
        resourcesTypes: ['xmlhttprequest'],
      },
      action: {
        type: 'modifyHeaders',
        requestHeaders: [{header: 'cookie', operation: 'set', value: cookie}],
      },
    }],
  });
  const res = await (await fetch(url, opts)).text();
  await chrome.declarativeNetRequest.updateSessionRules({
    removeRuleIds: [id],
  });
  return res;
}

Reply all
Reply to author
Forward
0 new messages