The Page Object
A Browser object can have many pages, which are individual browser tabs or popups. The page is the main interaction component between Playwright and the website.
The main functions of the Page object are:
- Navigate to web pages using the page.goto() and other functions.
- Select one or more elements from the current page using selectors.
- Interact with selected items by simulating clicking, typing and selecting options from dropdowns.
- Evaluating JavaScript in the current page.
- Exposing frames, which are embedded pages within the current page.
Evaluating JavaScript
Playwright is independent from the context the scripts on the web page are running. If JS code needs to be run on the current page, the page.evaluate() function is used.
page.evaluate(() => {return code... })
For example:
const data = { a: 1, b: 2 };
const result = await page.evaluate(async (data) => {
return await(data.a + data.b);
}, data);
console.log(result);
// returns 3;
Frames
A page frame is an independent web page embedded in the current page. These have a different DOM structure from the main page, and for that reason, they have to be selected before running any selectors or interactive functions.
The page exposes its own frame with the page.mainFrame() function, and its children frames (including iself) with the page.frames() function.
This is an example of getting a selector from an frame element:
const frame = page.frames().find(frame => frame.name() === 'myframe');
const element = await frame.$('.selector');
console.log(element);
For all purposes, a frame is used in the same way as the page object.