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?
var xhr = new XMLHttpRequest(); xhr. open("GET", url, false); xhr. withCredentials = true; xhr. setRequestHeader('Cookie', 'mycookie=cookie'); xhr.
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.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With