How to return the redirect URL with js?

Asked

Viewed 92 times

0

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

Below is as close as I got to getting it, but I can’t 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 get this in javascript? It doesn’t necessarily have to be with this code.

1 answer

1


Hi, this is Florida, You need to give getReturn to 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;
}

Browser other questions tagged

You are not signed in. Login or sign up in order to post.