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

前端 未结 5 520
花落未央
花落未央 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 03:17

    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;
      }
    });
    
     $.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'));
       }
      });
    

提交回复
热议问题