With javascript, how do you get the final result url after redirecting 302 to img src?

If there is an img tag on the page, the final image of which is displayed after the 302 redirect, is there a way with javascript to get that final URL after the redirect? Using javascript on img.src just gets the first URL (which is on the page), not what it was redirected to.

Here is a jsfiddle illustration: http://jsfiddle.net/jfriend00/Zp4zG/

+4
source share
5 answers

No, It is Immpossible. src is an attribute, and it does not change.

+4
source

I know this question is old, and the answer was already marked, but the other question I was trying to answer was marked as a duplicate of this, and I do not see any indications to any of the existing answers that you can get the true URL through the HTTP header. A simple example (assuming there is one image tag on your page) would be something like this ...

 var req = new XMLHttpRequest(); req.onreadystatechange=function() { if (req.readyState===4) {// && req.status===200) { alert("actual url: " + req.responseURL); } } req.open('GET', $('img').prop('src'), true); req.send(); 
+1
source

If you are open to using a third-party proxy, you can do this. Obviously not a javascript solution . This uses the proxy service from cors-anywhere.herokuapp.com. Just add this solution for people who are open to proxies and do not want to implement this in the backend.

Here is the fork of the original violin

 $.ajaxPrefilter( function (options) { if (options.crossDomain && jQuery.support.cors) { var http = (window.location.protocol === 'http:' ? 'http:' : 'https:'); options.url = http + '//cors-anywhere.herokuapp.com/' + options.url; //options.url = "http://cors.corsproxy.io/url=" + options.url; } }); $.ajax({ type: 'HEAD', //'GET' url:document.getElementById("testImage").src, success: function(data, textStatus, request){ alert(request.getResponseHeader('X-Final-Url')); }, error: function (request, textStatus, errorThrown) { alert(request.getResponseHeader('X-Final-Url')); } }); 
+1
source

based on http://jsfiddle.net/jfriend00/Zp4zG , these snippets work in Firefox 17.0:

 alert(document.getElementById("testImage").baseURI) 

In Chrome, this does not work. Nothing else verified -

0
source

Here is the workaround I found out. But it only works if the image is in the same domain otherwise you will get an empty string:

 var img = document.getElementById("img"); getSrc(img.getAttribute("src"), function (realSrc) { alert("Real src is: " + realSrc); }); function getSrc(src, cb) { var iframe = document.createElement("iframe"), b = document.getElementsByTagName("body")[0]; iframe.src = src; iframe.className = "hidden"; iframe.onload = function () { var val; try { val = this.contentWindow.location.href; } catch (e) { val = ""; } if (cb) { cb(val); } b.removeChild(this); }; b.appendChild(iframe); } 

http://jsfiddle.net/infous/53Layyhg/1/

0
source

All Articles