0

I need to write a Google App Script function that takes the redirected link from Google's "I feeling lucky" button.

The function should take:

http://www.google.com/search?q="stackoverflow"&btnI

and return:

https://stackoverflow.com

I've tried:

function getRedirect(url) {
  var response = UrlFetchApp.fetch(url, {'followRedirects': true, 'muteHttpExceptions': true});
  var redirectUrl = response.getHeaders()['Location']; // undefined if no redirect, so...
  var responseCode = response.getResponseCode();
  if (redirectUrl) {                                   // ...if redirected...
    var nextRedirectUrl = getRedirect(redirectUrl);    // ...it calls itself recursively...
    Logger.log(url + " is redirecting to " + redirectUrl + ". (" + responseCode + ")");
    return nextRedirectUrl;
  }
  else {                                               // ...until it's not
    Logger.log(url + " is canonical. (" + responseCode + ")");
    return url;
  }
}

But it doesn't work since it only handles http redirects -- I think Google's I'm feeling lucky button works differently.

  • I couldn't find a solution to this, so I just used PHP to get the final redirect via curl – sojim2 Dec 16 '18 at 20:17

Your Answer

By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.

Browse other questions tagged or ask your own question.