Accessing console logs in Playwright
Accessing console logs in the browser using Playwright is straightforward. You can use the page.on('console', callback)
method to listen for console events and capture logs.
Here's a step-by-step guide on how to do this:
Example
Here's a script to capture and log console messages from a webpage:
Playwright Script to Access Console Logs
const { chromium } = require('playwright');
(async () => {
// Launch the browser
const browser = await chromium.launch();
// Create a new browser context
const context = await browser.newContext();
// Create a new page
const page = await context.newPage();
// Listen for console messages
page.on('console', msg => {
console.log('Console message:', msg.text());
console.log('Type:', msg.type());
console.log('Location:', msg.location());
if (msg.type() === 'error') {
console.log('Error Text:', msg.text());
}
});
// Navigate to a webpage
await page.goto('https://example.com');
// Evaluate some script in the page context
await page.evaluate(() => {
console.log('This is a log message');
console.warn('This is a warning message');
console.error('This is an error message');
});
// Close the browser
await browser.close();
})();
Explanation
-
Launch the Browser:
const browser = await chromium.launch();
-
Create a New Browser Context:
const context = await browser.newContext();
-
Create a New Page:
const page = await context.newPage();
-
Listen for Console Messages:
page.on('console', msg => { console.log('Console message:', msg.text()); console.log('Type:', msg.type()); console.log('Location:', msg.location()); if (msg.type() === 'error') { console.log('Error Text:', msg.text()); } });
page.on('console', callback)
sets up a listener for console events.msg.text()
gets the text of the console message.msg.type()
gets the type of the console message (e.g.,log
,error
,warning
).msg.location()
gets the location in the source code where the console message was generated.
-
Navigate to a Webpage:
await page.goto('https://example.com');
-
Evaluate Some Script in the Page Context:
await page.evaluate(() => { console.log('This is a log message'); console.warn('This is a warning message'); console.error('This is an error message'); });
page.evaluate()
allows you to run JavaScript in the context of the webpage.- This script generates some console messages for demonstration purposes.
-
Close the Browser:
await browser.close();
Running the Script
Save the script to a file (e.g., capture_console_logs.js
) and execute it using Node.js:
node capture_console_logs.js
Published on: Jun 28, 2024, 03:23 AM