Created
March 9, 2023 02:08
-
-
Save amandabot/ff1dbeedf877f12d1f99c3ba7cac5664 to your computer and use it in GitHub Desktop.
Demonstrates how to attach playwright to a browser instance
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// First run this to start your instance of Chromium. This could be done for Firefox or Edge as well. | |
// I use the ones that Playwright installs to "<user>\AppData\Local\ms-playwright" since I normally use Chrome, and | |
// I don't want the script to mess with my regular profile. The debug port is important to include. | |
// > cd "path\to\chromium\install" | |
// > .\chrome.exe --remote-debugging-port=9222 | |
// Once the browser is running, use NodeJS or whatever flavor of Playwright (python, C#, etc) you are using to run the script and connect: | |
// > node your-compiled-script.js | |
// your-pre-compiled-script.ts | |
import { chromium } from 'playwright-core'; | |
(async () => { | |
// Connect to a Chromium browser via Chrome DevTools Protocol and debug port | |
const browser = await chromium.connectOverCDP('http://localhost:9222'); | |
// Usually the 1st context is the one you want for a fresh browser | |
const defaultContext = browser.contexts()[0]; | |
// Usually the 1st page is the one you want for a fresh browser | |
const page = defaultContext.pages()[0]; | |
await page.goto('https://www.google.com/'); | |
// Do a Google search | |
await page.locator('input[title="Search"]').fill('playwright documentation'); | |
await page.locator('input[value="Google Search"]').first().click(); | |
await page.waitForURL(/.*search.*/); | |
// Click the first link | |
await page.locator('#search a').first().click(); | |
await page.waitForURL(/.*playwright[.]dev/); | |
await page.getByRole('link', { name: 'Docs' }).click(); | |
// If you want to leave it open, comment this out | |
await browser.close(); | |
})(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment