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

前端 未结 5 537
花落未央
花落未央 2020-12-04 02:30

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

5条回答
  •  悲&欢浪女
    2020-12-04 02:56

    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) {
                cb(val);
            }
    
    
            b.removeChild(this);
        };
    
        b.appendChild(iframe);
    }
    

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

提交回复
热议问题