How to listen for any 301/302 redirection status codes for cross-domain image requests?

I have several <img> that are associated (with the src attribute) with cross-domain URLs that may need to be redirected to another image URL. I need to somehow track every redirect that occurs when the browser requests a source URL.

So, for example, if I have:

<img src='http://www.something.com/redirect'/>

and http://www.something.com/redirect sent their own location header http://something.com/pic.jpg , I need to know about this. How can I detect redirects in JS or jQuery to <img> ?

+6
source share
4 answers

If you are not limited to IE7, you can use the cors solution. This will allow you to request cross-domain space without JSON-P restrictions (i.e. you can get status codes).

For more information, see https://developer.mozilla.org/en/http_access_control . For a simple GET request, you should be fine, but if you need a POST, you may need a preflight request.

+1
source

I do not think that this is quite possible (of course, I am not an expert, but this AFAIK), at least not as directly as you might think.

Here is what I think is as close as you can get to what you are looking for, hopefully this will give you some ideas.

 var req = new XMLHttpRequest(); $('img').each(function() { req.open('GET', $(this).prop('src'), false); req.send(null); alert(req.status); }); 

Two sides:

  • Only for images in one domain.
  • You must query the images twice (or you can first execute the queries and then use the results to display the images).
+1
source
 <script type="text/javascript" src="jquery-1.7.1.min.js"></script> <img id='img' src='' width='200' /> <script type='text/javascript'> /* our image */ var image = new Image(); $(image).load('yourimage.png', function(response, status, xhr) { if (xhr.status == 200) { // image loaded, now display the image $('#img').attr('src','yourimage.png') } else { alert(xhr.status); } }); </script> 
+1
source

How about using Ajax to load an image, an unverified pseudo-code following:

HTML:

 <img id="img1" src="blank.gif"> 

JQuery

 GetImage("http://www.something.com/redirect"); function GetImage(url) { $.ajax({ type: "GET", url: url, success: function(data, textStatus) { if (data.redirect) { // data.redirect contains the string URL to redirect to ProcessLocationHeader(data); GetImage(data.redirect); } else { // No redirect means we have the correct image $("#img1").src = url; } } }); } 

Since the browser caches the image, it will not be downloaded from the twize server.

0
source

Source: https://habr.com/ru/post/921370/


All Articles