0

I have two domains, one which contains an image and another which is trying to access this picture. The following works for loading the image:

image = new Image(); 
image.src = "someotherdomain.com/picture.png";

However, I would like to send back some information as well. I cannot use AJAX due to Same-Origin-Policy. This is what I am trying to do:

image = new Image(); 
image.src = "someotherdomain.com/picture.png";

console.log(image.message); // How can I receive the message from the other server to here?

I cannot enable CORS or any of that.

High schooler
  • 1,682
  • 3
  • 30
  • 46

3 Answers3

1

If you want to send a GET request to the server, you can just set the path to the file

image.src = "http://example.com/some.php?message=" + encodeUriComponent("your string here");

Now the server can return a one pixel gif and it will work.

BUT modern day browsers support Ajax calls with CORS, so if the server sets the right headers to allow your domain, you can use the XMLHttpRequest object.


If you want to send data back, you will need to make a JSONP request.

function myCallback(obj) {
    console.log(obj);
}

var scr = document.createElement("script");
scr.src = "http://example.com/some.php?callback=myCallback&message=" + encodeUriComponent("your string here");
document.body.appendChild(scr);

and the server returns a script that looks like

myCallback({"hello" : "world"});
epascarello
  • 204,599
  • 20
  • 195
  • 236
0

If you are generating image on the server side or if you are able to modify it, it might be possible to add the message to the image exif data and than to parse and read it on the client side with JS with something like this: https://github.com/jseidelin/exif-js. (Of course that's probably not the smartest and the easiest way to send a message).

0

However, I would like to send back some information as well. I cannot use AJAX due to Same-Origin-Policy.

It is not allowed to read any data from a cross-origin-included image due to the exactly same Same-Origin-Policy that does forbid to read it via Ajax. You can only read image data by enabling CORS for the image file.

See also Ways to circumvent the same-origin policy.

Community
  • 1
  • 1
Bergi
  • 630,263
  • 148
  • 957
  • 1,375