Home > Software engineering >  unshorten ow.ly URL in Google Apps Script
unshorten ow.ly URL in Google Apps Script

Time:05-21

I use the following code (posted on stackoverflow.com) to unshorten URLs in Google App 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;
}

But when I use it for an ow.ly example URL:

function test() {
  Logger.log( ExpandURL("OWLYURL"))
}

I get the following message error in the log window:

Exception: Address unavailable: OWLYURL

(PLEASE replace OWLYURL with https://ow.ly /d9AV30jRJWJ (without space); since I cannot post my question when the body contains such plain URL)

The same thing happens for many other ow.ly URLs I've tried.

Is there any way to solve this issue?

CodePudding user response:

In your question, https:// ow . ly /d9AV30jRJWJ is used (Spaces are included because of avoiding the error of Stackoverflow.). But, I thought that in this case, it might be http:// ow . ly /d9AV30jRJWJ. Because when I accessed https:// ow . ly /d9AV30jRJWJ, no response is returned. On the other hand, when I accessed http:// ow . ly /d9AV30jRJWJ, the blog page is returned. If my understanding is correct, how about the following modification?

Modified script:

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

function test() {
  Logger.log(ExpandURL("http:// ow . ly /d9AV30jRJWJ")) // When you test this, please modify ` ow . ly ` to `ow.ly`.
}
  • When this test is run, https://blog.leadquizzes.com/ubersuggest-find-profitable-keywords-with-neil-patels-free-seo-tool?platform=hootsuite is returned.
  • Related