Skip to content

Instantly share code, notes, and snippets.

@evangow
Last active September 29, 2017 16:20
Show Gist options
  • Save evangow/04127e6bf69093acad18f27ef2e97ab0 to your computer and use it in GitHub Desktop.
Save evangow/04127e6bf69093acad18f27ef2e97ab0 to your computer and use it in GitHub Desktop.
How to make an authentication request with Facebook inside a chrome extension
authenticateWithFacebook = () => {
  return new Promise((resolve, reject) => {
    const TYPE = 'token';
    const RANDOM_STRING = uuid.v4();
    const URI = chrome.identity.getRedirectURL();
    const AUTH_URL = `https://www.facebook.com/v2.10/dialog/oauth?
          client_id=${CLIENT_ID}
          &redirect_uri=${URI}
          &state=${RANDOM_STRING}
          &response_type=${TYPE}`;
    chrome.identity.launchWebAuthFlow({
      url: AUTH_URL,
      interactive: true,
    }, function(redirectURL) {
      const searchParams = new URLSearchParams(redirectURL)
      const accessToken = searchParams.get('access_token');
      const secondsToExpiration = searchParams.get('expires_in');
      const tokenExpiration = Date.now() + secondsToExpiration * 1000

      const error = searchParams.get(URI + '?error')

      if (redirectURL == null) {
        reject(chrome.runtime.lastError.message)
      } else if (error) {
        reject(error);
      } else {
        resolve({
          accessToken: accessToken,
          tokenExpiration: tokenExpiration
        });
      }
    });
  });
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment