table of contents Table of contents

How to Automate Google Login with Playwright

On this page

Social login using your personal Google or Google Gsuite account is a common use case for many login scenarios.

Steps

  1. We start at a site that offers Google as an authentication provider. In this case we use Stack Overflow.
  2. We fetch the login page and click the “Login with Google” button.
  3. We are redirect to Google.
  4. We provide the username and password, injected by using environment variables.
  5. We are redirected back to the starting.
const { webkit } = require('playwright')

;(async () => {
  const browser = await webkit.launch()
  const page = await browser.newPage()

  await page.setViewport({ width: 1280, height: 800 })
  await page.goto('https://stackoverflow.com/users/login')

  await page.click('button.s-btn__google')

  await page.fill('input[type="email"]', process.env.GOOGLE_USER)
  await page.click('#identifierNext')

  await page.fill('input[type="password"]', process.env.GOOGLE_PWD)
  await page.click('#passwordNext')

  await browser.close()
})()

Run this example as follows. Replace the username and password placeholder with your own credentials.

GOOGLE_USER=username GOOGLE_PWD=password node google-login.js
SET GOOGLE_USER=username
SET GOOGLE_PWD=password
node google-login.js

This example does not work when you have 2-factor authentication enabled, and you might trigger a recaptcha check.

Takeaways

  1. Use environment variables to inject secrets.
  2. Wait for the navigation as your are redirected to Google.
  3. Wait for the navigation as you are redirected back to the start site.

Last updated on November 13, 2024. You can contribute to this documentation by editing this page on Github