title: Javascript: Get redirected link from Google's "I'm feeling lucky" function
body: <p>I need to write a Javascript function that takes the redirected link from Google's "I feeling lucky" button.</p>
  
  <p>The function should take:</p>
  
  <pre><code>http://www.google.com/search?q="stackoverflow"&amp;btnI
  </code></pre>
  
  <p>and return:</p>
  
  <pre><code>https://stackoverflow.com
  </code></pre>
  
  <p>I've tried:</p>
  
  <pre><code>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;
    }
  }
  </code></pre>
  
  <p>But it doesn't work since it only handles http redirects. I suppose Google's I'm feeling lucky button works differently.</p>