Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Send XHR request from Chrome extension with cookies

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?

like image 435
nathancahill Avatar asked Jun 18 '12 21:06

nathancahill


People also ask

How do I send cookies in XHR request?

var xhr = new XMLHttpRequest(); xhr. open("GET", url, false); xhr. withCredentials = true; xhr. setRequestHeader('Cookie', 'mycookie=cookie'); xhr.

What permission is required for a Chrome extension to make XHR request on any domain?

Most Chrome extension developers assume that if their website is www.mydomain.com, and their Chrome extension makes XHR requests to www.mydomain.com, then you must put www.mydomain.com in the permissions field of your manifest file.

How do I send a cookie with every request?

To send cookies to the server, you need to add the "Cookie: name=value" header to your request. To send multiple Cookies in one cookie header, you can separate them with semicolons. In this Send Cookies example, we are sending HTTP cookies to the ReqBin echo URL.

Can Chrome extensions make HTTP requests?

When building a Chrome extension, you can make cross-site XMLHttpRequests via Content Scripts or the Background Page. Content Scripts is JavaScript that can get injected into a webpage and can manipulate the page's DOM.


1 Answers

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.

like image 137
Quentin Avatar answered Oct 18 '22 15:10

Quentin