Reputation: 549
There's a script I'm fetching via dynamically adding a script tag. The script content sent back varies depending on the value of a certain cookie (say, server
) in the GET request for fetching the script.
I know that GET request for a <script>
will automatically carry all (permitted) cookies set in browser along with it. Can I add some of my own cookie values to this request in code?
The code I'm using is similar to this:
const script = document.createElement("script");
script.src = 'https://example.com/script';
script.onload = () => console.log("Loaded!");
document.body.appendChild(script);
Upvotes: 0
Views: 1271
Reputation: 177786
If you change the cookie before the .src statement, it will be sent to the server IIF the server is the same as from where the page was loaded.
You cannot set a cookie on domainA that is sent to domainB regardless that you can load a script from domainB
NOTE: The correct order is this - ALWAYS set the load handler BEFORE setting the src of anything; the server can respond with the file before the next statement is read.
Also we normally append the script to the head. This will also work after the page has loaded.
// change cookie here
const script = document.createElement("script");
script.onload = () => console.log("Loaded!");
// or change cookie here
script.src = 'https://example.com/script';
document.querySelector("head").appendChild(script);
Upvotes: 1