Reuse Cookie and LocalStorage
In most cases, authentication state is stored in cookie or local storage. When we just want to keep authenticated, it is a good solution to dump/load 'storage state' (= Cookie + LocalStorage). https://playwright.dev/docs/next/auth#reuse-authentication-state
- Dump storage state using BrowserContext#storage_state with
- Load storage state by specifying the parameter
storageState: /path/to/state.jsoninto Browser#new_context or Browser#new_page
Generally in browser automation, it is very difficult to bypass 2FA or reCAPTCHA in login screen. In such cases, we would consider
- Authenticate manually by hand
- Resume automation with the authentication result
force_login = !File.exist?('github_state.json')
Playwright.create(playwright_cli_executable_path: 'npx playwright') do |playwright|
# Use headful mode for manual operation.
playwright.chromium.launch(headless: false, channel: 'chrome') do |browser|
page = browser.new_page
# Login manually.
playwright.chromium.launch do |browser|
page = browser.new_page(storageState: 'github_state.json')
When we execute this script at the first time (without github_state.json), login screen is shown:
and input credentials manually:
exit in Pry console.
10: # Login manually. Hit `exit` in Pry console after authenticated.
11: require 'pry'
=> 14: page.context.storage_state(path: 'github_state.json')
15: end if force_login
17: playwright.chromium.launch do |browser|
18: page = browser.new_page(storageState: 'github_state.json')
 pry(main)> exit
then we can enjoy automation with keeping authenticated. Login screen is never shown until github_state.json is deleted :)