How to send cookies in an Image() constructor

时间:2015-10-30 22:13:44

标签: javascript image cookies

I'm injecting an image into a canvas that I have to get securely by passing cookies with my request. My issue is that the Image constructor doesn't seem to send the cookies with the request when the src is set. The cookies are not accessible through js, they are sent by the browser.

var img = new Image();
img.setAttribute('crossOrigin', 'anonymous');

validateUrl(originalUrl, function (validatedUrl) {
    img.src = validatedUrl; //GET fails after this happens
});

img.onload = function () {
   drawImageProp(context, img);
}

1 个答案:

答案 0 :(得分:1)

If you set the crossorigin attribute on an image, then cookies are not sent with the request for the image. That's how that feature is written to work.

Cookies are tied to a specific domain/subdomain (and optionally to a path within that domain). When requesting an image, any cookies for the domain that the image is being requested from will be automatically sent with the image request.

The browser only gives Javascript access to cookies that are in the same origin as the host web page. So, Javascript has no ability to read cookies for some other domain.

So, when you request your image by setting the .src property, any cookies that belong to the domain of the image URL will be sent with the image request automatically (you don't do anything to cause that).