Rayrun

What are the functionalities of the Page class in Playwright and how can I use them?

Answer

Working with the Page Class in Playwright

The Page class in Playwright is your main tool for interacting with a single tab in a browser or an extension background page in Chromium.

Creating a New Page

You can create a new page using the newPage() method of the context object.

const context = await browser.newContext();
const page = await context.newPage();

Navigating to a URL

Once you have a page, you can navigate it to a URL using the goto() method.

await page.goto('https://ray.run/');

Taking Screenshots

You can take screenshots using the screenshot() method.

await page.screenshot({ path: 'example.png' });

Handling Page Events

The Page class emits various events that you can handle using Node's native EventEmitter methods such as on, once, or removeListener.

page.once('load', () => console.log('Page loaded!'));

function logRequest(interceptedRequest) {
  console.log('A request was made:', interceptedRequest.url());
}

page.on('request', logRequest);

// Sometime later...
page.removeListener('request', logRequest);

Adding Initialization Scripts

Use the addInitScript() method to add scripts that are evaluated whenever the page is navigated or a child frame is attached or navigated.

await page.addInitScript(() => {
  // This will run before any script on the page.
});

Other Page Methods

The Page class also provides methods for mouse and keyboard interactions (mouse, keyboard), API testing helpers (request), touchscreen interactions (touchscreen), and events like 'close', 'console', and 'crash'.

References

Thank you!
Was this helpful?
Still have questions?

If you still have questions, please ask a question and I will try to answer it.

Related Questions

TwitterGitHubLinkedIn
AboutQuestionsDiscord ForumBrowser ExtensionTagsQA Jobs

Rayrun is a community for QA engineers. I am constantly looking for new ways to add value to people learning Playwright and other browser automation frameworks. If you have feedback, email luc@ray.run.