Reputation: 298
I'm loading [site1]/script.js on [site2]/page.html with script
tag.
And the browser does not send cookies while requesting a JS file.
Response headers:
HTTP/1.1 200 OK Server: nginx Date: Thu, 02 Apr 2015 14:45:38 GMT Content-Type: application/javascript Content-Length: 544 Connection: keep-alive Content-Location: script.js.php Vary: negotiate,Accept-Encoding TCN: choice Set-Cookie: test_id=551d5612406cd; expires=Sat, 02-Apr-2016 14:45:38 GMT; path=/ Content-Encoding: gzip
Request headers - no cookies:
GET /script.js HTTP/1.1 Host: [site1] Connection: keep-alive Cache-Control: max-age=0 Accept: */* User-Agent: Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/41.0.2272.101 Safari/537.36 Referer: [site2]/page.html Accept-Encoding: gzip, deflate, sdch Accept-Language: ru,en-US;q=0.8,en;q=0.6,sk;q=0.
Upvotes: 10
Views: 13831
Reputation: 20816
There is a special case where cookies are not sent, even though the origin is the same: when loading ES6 modules!
<script type="module" src="some-script.js"></script>
This won't send cookies, so it might fail if your server needs to authenticate requests.
As this excellent article points out, you need to explicitly require credentials to be sent by adding the
crossorigin
attribute:
<script type="module" crossorigin src="some-script.js"></script>
This behavior is currently considered a bug (it doesn't make any sense, right?) and it's being fixed in all major browsers. See the link above for more details.
Upvotes: 16
Reputation: 298
Sorry, it was my mistake. Google Chrome was blocking third-party cookies.
By default browser send cookies with JavaScript file request.
Upvotes: 1
Reputation: 1075337
Browsers do send cookies when requesting JavaScript files, just as they do when requesting anything else. And the same rules apply: The cookie must be for the origin/path. In your example, you seem to be using two different origins (site1
and site2
), which would explain why you don't see the cookie in the request.
For instance: I set up a page called test.php
on my server that sets a cookie. It then has a link to test2.html
which includes foo.js
. These are all on the same path (/
, in my example, because I'm lazy and didn't create a subdirectory for the test).
In the response headers when the browser gets test.php
, I see
Set-Cookie:test=123
If I then click to test2.html
, I see this in the request headers for test2.html
:
Cookie:test=123
And then I see the request for foo.js
, and in that request I see:
Cookie:test=123
Upvotes: 6