Search code examples
functiongoogle-apps-scripturlexpand

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!


Solution

  • 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: