10

I'm trying to send an XHR request from a Google Chrome extension to another domain. This would work fine, but I need to send that domains cookies with the request. Any way to do this?

nathancahill
  • 10,452
  • 9
  • 51
  • 91
  • You can use the [`webRequest`](http://code.google.com/chrome/extensions/webRequest.html#event-onBeforeSendHeaders) API to modify headers, including `Cookie`. An example of UA spoofing + header editing can be found [here](http://stackoverflow.com/a/10339902/938089?associate-a-custom-user-agent-to-a-specific-google-chrome-page-tab). – Rob W Jun 18 '12 at 21:45
  • Why are you under the impression that Chrome will not send the user's cookies? I just tested it, and it does. Is the site in your permissions? – Pixievolt No. 1 Jun 19 '12 at 06:00
  • Huh. My bad. It definitely does send cookies with the request. – nathancahill Jun 20 '12 at 02:31
  • 1
    What ajax library are you guys doing? jQuery isn't sending it..do I need to use native XHR or something? – Tallboy Jul 01 '18 at 16:45

1 Answers1

9

Make sure the manifest.json permissions are setup properly.

You have to properly set the cross site domain request permission in the manifest.json of your chrome extension. When done properly, the cookies who are already set for the targeted domain will be sent along with the request you are making to that domain. manifest.json documentation

You have to be especially careful when playing with localhost:port_number. You will need to specify that domain in full in the manifest.json for it to work. I ended up with awkward behaviors when my localhost domain was NOT specify in full.

This is how you want to specify your localhost domain in the manifest.json of your extension (if that makes sense):

...
"permissions": [
    "http://localhost:3000/"
  ],
...

If the cookies you want to send to the targeted domain are not set yet, you can do so my using the chrome.cookies.set method and specify the domain name you want through the object domain attribute you pass to the set method. The documentation is here: chrome.cookies.set.

Quentin
  • 1,854
  • 1
  • 19
  • 19
  • 2
    Why does localhost give cross site permissions? – itchyspacesuit Feb 18 '17 at 17:28
  • I have problem with "incognito". Chrome uses "normal mode cookies", how to use "incognito cookies" for that mode? – mixalbl4 Oct 12 '18 at 14:04
  • you also want to make sure the cookie path match, what I found out is a cookie set at path `/a` won't be sent to url `/b`; a cookie set at path `/` will be sent to all urls under same domain though. – xysun Dec 20 '20 at 22:44