简体   繁体   English

使用Javascript通过图像发送消息

[英]Send message through image with Javascript

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. 由于相同原产地政策,我无法使用AJAX。 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. 我无法启用CORS或任何其他功能。

If you want to send a GET request to the server, you can just set the path to the file 如果要将GET请求发送到服务器,则只需将路径设置为文件

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. 现在,服务器可以返回一个1像素的gif,它将可以正常工作。

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. 但是,现代的浏览器通过CORS支持Ajax调用,因此,如果服务器设置正确的标头以允许您的域,则可以使用XMLHttpRequest对象。


If you want to send data back, you will need to make a JSONP request . 如果您想发回数据,则需要发出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"});

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 . 如果要在服务器端生成图像,或者可以对其进行修改,则可以将消息添加到图像exif数据中,然后可以使用如下所示的JS在客户端解析和读取该消息: https ://github.com/jseidelin/exif-js (Of course that's probably not the smartest and the easiest way to send a message). (当然,这可能不是发送消息的最聪明,最简单的方法)。

However, I would like to send back some information as well. 但是,我也想发回一些信息。 I cannot use AJAX due to Same-Origin-Policy. 由于相同原产地政策,我无法使用AJAX。

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. 由于完全相同的Same-Origin-Policy确实禁止通过Ajax读取数据,因此不允许从包含跨域的图像读取任何数据。 You can only read image data by enabling CORS for the image file. 您只能通过为图像文件启用CORS来读取图像数据。

See also Ways to circumvent the same-origin policy . 另请参阅规避同源政策的方法

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM