Playwright Browser Launch
Slide 1: Introduction to Playwright Browser Launch
Playwright is a Node.js library for browser automation, supporting multiple browsers like Chromium, Firefox, and WebKit. This tutorial demonstrates how to launch a browser manually, open a page, and navigate to a website.
Slide 2: Code Breakdown
const browser = await chromium.launch({ channel: 'chrome' })
Launch Chromium: The
chromium.launch()
function starts the Chromium browser (or any other browser you specify).channel: 'chrome'
: This specifies that Playwright should use the Google Chrome installation if available.Other Options:
'msedge'
for Microsoft Edge'firefox'
for Mozilla Firefox'webkit'
for WebKit (Safari)
Slide 3: Creating a Context
const context = await browser.newContext()
New Context: Creates a new browser context.
A context is like an incognito window. It isolates cookies, storage, and other data from the main browser session.
Why Use Context?: Allows multiple sessions to run independently (e.g., testing different logins at the same time).
Slide 4: Opening a Page
const page1 = await context.newPage()
New Page: Opens a new tab within the browser context.
A page is where all actions (e.g., navigation, clicks, form filling) occur.
Slide 5: Navigation to Google
await page1.goto('https://www.google.com')
goto()
: Navigates the page to the specified URL (in this case, Google).Why Use: This is the starting point for automation (loading a website).
Slide 6: Optional Enhancements
Headless Mode: By default, Playwright runs browsers in headless mode (no GUI). To see the browser, set:
headless: false
Slow Motion: You can slow down actions for debugging:
slowMo: 50 // Delay each action by 50ms
Error Handling:
Add
try-catch
blocks to handle errors safely.Always close the browser in a
finally
block to prevent hanging processes.
Slide 7: Full Example with Error Handling
const { chromium } = require('playwright'); // Import Playwright
(async () => {
try {
const browser = await chromium.launch({ headless: false, channel: 'chrome' });
const context = await browser.newContext();
const page = await context.newPage();
await page.goto('https://www.google.com');
await page.waitForTimeout(5000); // Optional: Pause for 5 seconds to observe
} catch (error) {
console.error('Error:', error); // Log any errors
} finally {
await browser.close(); // Ensure browser is closed
}
})();
finally
block: Ensures the browser is closed even if an error occurs.