StekolschikovV
StekolschikovV

Reputation: 41

Chrome extension: how can I intercept a cookie?

I need to grab the event when the page loads, when the cookies are sent and change them.

onBeforeRequest ---> my code ---> set cookie ---> set request

I found this event - chrome.webRequest.onBeforeRequest.

In all the articles and the documentation says that I need to ask for cookies in the details.requestHeaders:

chrome.webRequest.onBeforeRequest.addListener(
function (details) {
   console.log(details.requestHeaders)
},
{ urls: ["<all_urls>"] },
["blocking"]);

But it is always undefined.

How to solve my problem?

Upvotes: 2

Views: 1931

Answers (2)

Joe
Joe

Reputation: 387

The below code works for me.

You have to have extraHeaders if you want to see cookies in the response.

Note that your optional arguments might be different depending on the method you use (e.g. onBeforeSendHeaders, onCompleted, onHeadersReceived, etc.). Here's the docs for onCompleted. You can find the available options there.

    async function readCookies() {
  chrome.webRequest.onCompleted.addListener(
    (details) => {
      const cookies = [];
      details.responseHeaders.forEach((h) => {
        if (h.name == "set-cookie") {
          cookies.push(h.value.split(";")[0]);
        }
      });
      console.log("Details: ", details);
      console.log("Cookies: ", cookies);
      return details;
    },
    { urls: ["*://*.google.com/*"] },
    ["responseHeaders", "extraHeaders"]
  );
}

Upvotes: 0

kundrata
kundrata

Reputation: 679

You can only read the request headers using the events onBeforeSendHeadersand onHeadersReceived

Also, you need to add "requestHeaders" to the optional argument. Example:

chrome.webRequest.onBeforeSendHeaders.addListener(
          //
          // details.requestHeaders // check me out
          return {requestHeaders: details.requestHeaders};
        },
        {urls: ["<all_urls>"]},
        ["blocking", "requestHeaders"]);

Upvotes: 1

Related Questions