With javascript, how do you get final result URL after 302 redirect on img src?

If there is an img tag in a page whose final image it displays comes after a 302 redirect, is there a way with javascript to obtain what that final URL is after the redirect? Using javascript on img.src just gets the first URL (what's in the page), not what it was redirected to.

Here's a jsfiddle illustration: http://jsfiddle.net/jfriend00/Zp4zG/



No, this is not possible. src is an attribute and it does not change.


I know this question is old, and was already marked answered, but another question that I was trying to answer was marked as a duplicate of this, and I don't see any indication in any of the existing answers that you can get the true URL via the HTTP header. A simple example (assuming a single 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);

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

Here is a fork of the original fiddle

$.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;

   type: 'HEAD', //'GET'
   success: function(data, textStatus, request){
   error: function (request, textStatus, errorThrown) {

based on http://jsfiddle.net/jfriend00/Zp4zG, this snippets works in Firefox 17.0:


It doesn't work in Chrome. Not tested anything else-


Here is a workaround that I found out. But it works only if the image on 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) {





Recent Questions

Top Questions

Home Tags Terms of Service Privacy Policy DMCA Contact Us

©2020 All rights reserved.