简体   繁体   中英

Unshorten URL in Google Sheets

I want to unshorten a URL using a custom Function via Google App Script. I tried with this code but it didn't work.

function ExpandURL(url){
  var response = UrlFetchApp.fetch(url,{followRedirects: false});
  var longurl = decodeURIComponent(response.getHeaders()['Location'])
return longurl;
}

For example, I want to reveal the original of this link t.ly/1lzC - which is www.google.com - using a function in Google Sheets. Please help me out. Thank you so much!

When I saw your script, I thought that your script works. But, from I tried with this code but it didn't work. in your question, there is one thing that I'm worried about. I think that your script returns https://www.google.com when https://t.ly/1lzC is used as url . But, when t.ly/1lzC is used as url , https://www.google.com cannot be obtained. Please be careful about this.

If you want to use your script as the custom function like =ExpandURL(A1) that A1 is t.ly/1lzC , please modify it to =ExpandURL("https://"&A1) . By this, https://www.google.com is returned.

Or, when you want to modify your script, how about the following modification?

Modified script:

function ExpandURL(url) {
  url = url.indexOf("https://") == 0 ? url : "https://" + url;  // Added
  var response = UrlFetchApp.fetch(url, { followRedirects: false });
  var longurl = decodeURIComponent(response.getHeaders()['Location']);
  return longurl;
}

Reference:

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM