How to return the redirect URL with js?

0

I have a URL that redirects to another URL where Location is with the final URL, I want to return a var urlfinal only the final URL that is in this Location , not the URL that is heading there.

Below is the closest I've come to achieving this, but I can not seem to make a return urlfinal for example.

Code:

function RetornaUrlFinal(url){
const url = redirect;
let bloburl = void 0;
let img = new Image;
const getResourceName = fetch(url)
    .then(response => Promise.all([response.url, response.blob()]))
    .then(([resource, blob]) => {
      bloburl = URL.createObjectURL(blob);
      img.src = bloburl;
      document.body.appendChild(img);
      return resource
    });
    getResourceName.then(res => console.log(res)).catch(err => console.log(err))
    //return urlfinal;
}


Code, second attempt fails:

function testRedirect(url) {
  var xhr = new XMLHttpRequest();
  var urlredirect;
  xhr.onreadystatechange = function(e) {
    if (xhr.status == 200 && xhr.readyState == 4) {
      if (url != xhr.responseURL) {
        //alert("redirect detected to: " + xhr.responseURL)
        return xhr.responseURL;
        console.log("URL:" + xhr.responseURL);
      } else {
        console.log("Erro na URL:" + xhr.responseURL);
      }
    }
  }
  xhr.open("GET", url, true);
  xhr.send();
}

Is there any way to achieve this in javascript? It does not necessarily have to be with this code.

    
asked by anonymous 08.05.2018 / 02:54

1 answer

1

Talk to Florida, You need to give a return in getResourceName and treat this function as promisse.

Example:

function redirecionarComNovaUrl(){
    RetornaUrlFinal(url)
    .then(res => { window.location = res.url; })
    .catch(err => console.log(err));
}

function RetornaUrlFinal(url){
const url = redirect;
let bloburl = void 0;
let img = new Image;
const getResourceName = fetch(url)
    .then(response => Promise.all([response.url, response.blob()]))
    .then(([resource, blob]) => {
      bloburl = URL.createObjectURL(blob);
      img.src = bloburl;
      document.body.appendChild(img);
      return resource
    });
    return getResourceName;
}
    
21.05.2018 / 20:31