Why The Browser Doesn't Send Cookies While Requesting A JavaScript File?
Solution 1:
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.
Solution 2:
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
Solution 3:
Sorry, it was my mistake. Google Chrome was blocking third-party cookies.
By default browser send cookies with JavaScript file request.
Post a Comment for "Why The Browser Doesn't Send Cookies While Requesting A JavaScript File?"