class: Page

class: Page

Page provides methods to interact with a single tab in a Browser, or an extension background page in Chromium. One Browser instance might have multiple Page instances.

This example creates a page, navigates it to a URL, and then saves a screenshot:

const { webkit } = require('playwright');  // Or 'chromium' or 'firefox'.

(async () => {
  const browser = await webkit.launch();
  const context = await browser.newContext();
  const page = await context.newPage();
  await page.goto('https://example.com');
  await page.screenshot({path: 'screenshot.png'});
  await browser.close();
})();

The Page class emits various events (described below) which can be handled using any of Node‘s native EventEmitter methods, such as on, once or removeListener.

This example logs a message for a single page load event:

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

To unsubscribe from events use the removeListener method:

function logRequest(interceptedRequest) {
  console.log('A request was made:', interceptedRequest.url());
}
page.on('request', logRequest);
// Sometime later...
page.removeListener('request', logRequest);
  • event: ‘close’
  • event: ‘console’
  • event: ‘crash’
  • event: ‘dialog’
  • event: ‘domcontentloaded’
  • event: ‘download’
  • event: ‘filechooser’
  • event: ‘frameattached’
  • event: ‘framedetached’
  • event: ‘framenavigated’
  • event: ‘load’
  • event: ‘pageerror’
  • event: ‘popup’
  • event: ‘request’
  • event: ‘requestfailed’
  • event: ‘requestfinished’
  • event: ‘response’
  • event: ‘worker’
  • page.$(selector)
  • page.$$(selector)
  • page.$eval(selector, pageFunction[, arg])
  • page.$$eval(selector, pageFunction[, arg])
  • page.accessibility
  • page.addInitScript(script[, arg])
  • page.addScriptTag(options)
  • page.addStyleTag(options)
  • page.check(selector, [options])
  • page.click(selector[, options])
  • page.close([options])
  • page.content()
  • page.context()
  • page.coverage
  • page.dblclick(selector[, options])
  • page.dispatchEvent(selector, type[, eventInit, options])
  • page.emulateMedia(options)
  • page.evaluate(pageFunction[, arg])
  • page.evaluateHandle(pageFunction[, arg])
  • page.exposeBinding(name, playwrightBinding)
  • page.exposeFunction(name, playwrightFunction)
  • page.fill(selector, value[, options])
  • page.focus(selector[, options])
  • page.frame(options)
  • page.frames()
  • page.getAttribute(selector, name[, options])
  • page.goBack([options])
  • page.goForward([options])
  • page.goto(url[, options])
  • page.hover(selector[, options])
  • page.innerHTML(selector[, options])
  • page.innerText(selector[, options])
  • page.isClosed()
  • page.keyboard
  • page.mainFrame()
  • page.mouse
  • page.opener()
  • page.pdf([options])
  • page.press(selector, key[, options])
  • page.reload([options])
  • page.route(url, handler)
  • page.screenshot([options])
  • page.selectOption(selector, values[, options])
  • page.setContent(html[, options])
  • page.setDefaultNavigationTimeout(timeout)
  • page.setDefaultTimeout(timeout)
  • page.setExtraHTTPHeaders(headers)
  • page.setInputFiles(selector, files[, options])
  • page.setViewportSize(viewportSize)
  • page.textContent(selector[, options])
  • page.title()
  • page.type(selector, text[, options])
  • page.uncheck(selector, [options])
  • page.unroute(url[, handler])
  • page.url()
  • page.viewportSize()
  • page.waitForEvent(event[, optionsOrPredicate])
  • page.waitForFunction(pageFunction[, arg, options])
  • page.waitForLoadState([state[, options]])
  • page.waitForNavigation([options])
  • page.waitForRequest(urlOrPredicate[, options])
  • page.waitForResponse(urlOrPredicate[, options])
  • page.waitForSelector(selector[, options])
  • page.waitForTimeout(timeout)
  • page.workers()

event: ‘close’

Emitted when the page closes.

event: ‘console’

  • <ConsoleMessage>

Emitted when JavaScript within the page calls one of console API methods, e.g. console.log or console.dir. Also emitted if the page throws an error or a warning.

The arguments passed into console.log appear as arguments on the event handler.

An example of handling console event:

page.on('console', msg => {
  for (let i = 0; i < msg.args().length; ++i)
    console.log(`${i}: ${msg.args()[i]}`);
});
page.evaluate(() => console.log('hello', 5, {foo: 'bar'}));

event: ‘crash’

Emitted when the page crashes. Browser pages might crash if they try to allocate too much memory. When the page crashes, ongoing and subsequent operations will throw.

The most common way to deal with crashes is to catch an exception:

try {
  // Crash might happen during a click.
  await page.click('button');
  // Or while waiting for an event.
  await page.waitForEvent('popup');
} catch (e) {
  // When the page crashes, exception message contains 'crash'.
}

However, when manually listening to events, it might be useful to avoid stalling when the page crashes. In this case, handling crash event helps:

await new Promise((resolve, reject) => {
  page.on('requestfinished', async request => {
    if (await someProcessing(request))
      resolve(request);
  });
  page.on('crash', error => reject(error));
});

event: ‘dialog’

  • <Dialog>

Emitted when a JavaScript dialog appears, such as alert, prompt, confirm or beforeunload. Playwright can respond to the dialog via Dialog‘s accept or dismiss methods.

event: ‘domcontentloaded’

Emitted when the JavaScript DOMContentLoaded event is dispatched.

event: ‘download’

  • <Download>

Emitted when attachment download started. User can access basic file operations on downloaded content via the passed Download instance.

NOTE Browser context must be created with the acceptDownloads set to true when user needs access to the downloaded content. If acceptDownloads is not set or set to false, download events are emitted, but the actual download is not performed and user has no access to the downloaded files.

event: ‘filechooser’

  • <FileChooser>

Emitted when a file chooser is supposed to appear, such as after clicking the <input type=file>. Playwright can respond to it via setting the input files using fileChooser.setFiles that can be uploaded after that.

page.on('filechooser', async (fileChooser) => {
  await fileChooser.setFiles('/tmp/myfile.pdf');
});

event: ‘frameattached’

  • <Frame>

Emitted when a frame is attached.

event: ‘framedetached’

  • <Frame>

Emitted when a frame is detached.

event: ‘framenavigated’

  • <Frame>

Emitted when a frame is navigated to a new url.

event: ‘load’

Emitted when the JavaScript load event is dispatched.

event: ‘pageerror’

  • <Error “Error”)> The exception message

Emitted when an uncaught exception happens within the page.

event: ‘popup’

  • <Page> Page corresponding to “popup” window

Emitted when the page opens a new tab or window. This event is emitted in addition to the browserContext.on('page'), but only for popups relevant to this page.

The earliest moment that page is available is when it has navigated to the initial url. For example, when opening a popup with window.open('http://example.com'), this event will fire when the network request to “http://example.com” is done and its response has started loading in the popup.

const [popup] = await Promise.all([
  page.waitForEvent('popup'),
  page.evaluate(() => window.open('https://example.com')),
]);
console.log(await popup.evaluate('location.href'));

NOTE Use page.waitForLoadState([state[, options]]) to wait until the page gets to a particular state (you should not need it in most cases).

event: ‘request’

  • <Request>

Emitted when a page issues a request. The request object is read-only. In order to intercept and mutate requests, see page.route() or browserContext.route().

event: ‘requestfailed’

  • <Request>

Emitted when a request fails, for example by timing out.

NOTE HTTP Error responses, such as 404 or 503, are still successful responses from HTTP standpoint, so request will complete with 'requestfinished' event and not with 'requestfailed'.

event: ‘requestfinished’

  • <Request>

Emitted when a request finishes successfully.

event: ‘response’

  • <Response>

Emitted when a response is received.

event: ‘worker’

  • <Worker>

Emitted when a dedicated WebWorker is spawned by the page.

page.$(selector)

  • selector <string “String”)> A selector to query page for. See working with selectors for more details.
  • returns: <Promise “Promise”)<?ElementHandle>>

The method finds an element matching the specified selector within the page. If no elements match the selector, the return value resolves to null.

Shortcut for page.mainFrame().$(selector).

page.$$(selector)

  • selector <string “String”)> A selector to query page for. See working with selectors for more details.
  • returns: <Promise “Promise”)<Array ”Array“)<ElementHandle>>>

The method finds all elements matching the specified selector within the page. If no elements match the selector, the return value resolves to [].

Shortcut for page.mainFrame().$$(selector).

page.$eval(selector, pageFunction[, arg])

  • selector <string “String”)> A selector to query page for. See working with selectors for more details.
  • pageFunction <function “Function”)(Element ”Element“))> Function to be evaluated in browser context
  • arg <Serializable “Serializable”)|JSHandle> Optional argument to pass to pageFunction
  • returns: <Promise “Promise”)<Serializable ”Serializable“)>> Promise which resolves to the return value of pageFunction

The method finds an element matching the specified selector within the page and passes it as a first argument to pageFunction. If no elements match the selector, the method throws an error.

If pageFunction returns a Promise “Promise”), then page.$eval would wait for the promise to resolve and return its value.

Examples:

const searchValue = await page.$eval('#search', el => el.value);
const preloadHref = await page.$eval('link[rel=preload]', el => el.href);
const html = await page.$eval('.main-container', (e, suffix) => e.outerHTML + suffix, 'hello');

Shortcut for page.mainFrame().$eval(selector, pageFunction).

page.$$eval(selector, pageFunction[, arg])

  • selector <string “String”)> A selector to query page for. See working with selectors for more details.
  • pageFunction <function “Function”)(Array ”Array“)<Element “Element”)>)> Function to be evaluated in browser context
  • arg <Serializable “Serializable”)|JSHandle> Optional argument to pass to pageFunction
  • returns: <Promise “Promise”)<Serializable ”Serializable“)>> Promise which resolves to the return value of pageFunction

The method finds all elements matching the specified selector within the page and passes an array of matched elements as a first argument to pageFunction.

If pageFunction returns a Promise “Promise”), then page.$$eval would wait for the promise to resolve and return its value.

Examples:

const divsCounts = await page.$$eval('div', (divs, min) => divs.length >= min, 10);

page.accessibility

  • returns: <Accessibility>

page.addInitScript(script[, arg])

  • script <function “Function”)|string ”String“)|Object “Object”)> Script to be evaluated in the page.
    • path <string “String”)> Path to the JavaScript file. If path is a relative path, then it is resolved relative to current working directory.
    • content <string “String”)> Raw script content.
  • arg <Serializable “Serializable”)> Optional argument to pass to script (only supported when passing a function).
  • returns: <Promise “Promise”)>

Adds a script which would be evaluated in one of the following scenarios:

  • Whenever the page is navigated.
  • Whenever the child frame is attached or navigated. In this case, the scritp is evaluated in the context of the newly attached frame.

The script is evaluated after the document was created but before any of its scripts were run. This is useful to amend the JavaScript environment, e.g. to seed Math.random.

An example of overriding Math.random before the page loads:

// preload.js
Math.random = () => 42;

// In your playwright script, assuming the preload.js file is in same folder
const preloadFile = fs.readFileSync('./preload.js', 'utf8');
await page.addInitScript(preloadFile);

NOTE The order of evaluation of multiple scripts installed via browserContext.addInitScript(script[, arg]) and page.addInitScript(script[, arg]) is not defined.

page.addScriptTag(options)

  • options <Object “Object”)>
    • url <string “String”)> URL of a script to be added.
    • path <string “String”)> Path to the JavaScript file to be injected into frame. If path is a relative path, then it is resolved relative to current working directory.
    • content <string “String”)> Raw JavaScript content to be injected into frame.
    • type <string “String”)> Script type. Use ‘module’ in order to load a Javascript ES6 module. See script for more details.
  • returns: <Promise “Promise”)<ElementHandle>> which resolves to the added tag when the script‘s onload fires or when the script content was injected into frame.

Adds a <script> tag into the page with the desired url or content.

Shortcut for page.mainFrame().addScriptTag(options).

page.addStyleTag(options)

  • options <Object “Object”)>
    • url <string “String”)> URL of the <link> tag.
    • path <string “String”)> Path to the CSS file to be injected into frame. If path is a relative path, then it is resolved relative to current working directory.
    • content <string “String”)> Raw CSS content to be injected into frame.
  • returns: <Promise “Promise”)<ElementHandle>> which resolves to the added tag when the stylesheet‘s onload fires or when the CSS content was injected into frame.

Adds a <link rel="stylesheet"> tag into the page with the desired url or a <style type="text/css"> tag with the content.

Shortcut for page.mainFrame().addStyleTag(options).

page.check(selector, [options])

  • selector <string “String”)> A selector to search for checkbox or radio button to check. If there are multiple elements satisfying the selector, the first will be checked. See working with selectors for more details.
  • options <Object “Object”)>
    • force <boolean “Boolean”)> Whether to bypass the actionability checks. Defaults to false.
    • noWaitAfter <boolean “Boolean”)> Actions that initiate navigations are waiting for these navigations to happen and for pages to start loading. You can opt out of waiting via setting this flag. You would only need this option in the exceptional cases such as navigating to inaccessible pages. Defaults to false.
    • timeout <number “Number”)> Maximum time in milliseconds, defaults to 30 seconds, pass 0 to disable timeout. The default value can be changed by using the browserContext.setDefaultTimeout(timeout) or page.setDefaultTimeout(timeout) methods.
  • returns: <Promise “Promise”)> Promise which resolves when the element matching selector is successfully checked. The Promise will be rejected if there is no element matching selector.

This method fetches an element with selector, if element is not already checked, it scrolls it into view if needed, and then uses page.click to click in the center of the element. If there‘s no element matching selector, the method waits until a matching element appears in the DOM. If the element is detached during the actionability checks, the action is retried.

Shortcut for page.mainFrame().check(selector[, options]).

page.click(selector[, options])

  • selector <string “String”)> A selector to search for element to click. If there are multiple elements satisfying the selector, the first will be clicked. See working with selectors for more details.
  • options <Object “Object”)>
    • button <“left”|”right“|“middle”> Defaults to left.
    • clickCount <number “Number”)> defaults to 1. See UIEvent.detail ”UIEvent.detail“).
    • delay <number “Number”)> Time to wait between mousedown and mouseup in milliseconds. Defaults to 0.
    • position <Object “Object”)> A point to click relative to the top-left corner of element padding box. If not specified, clicks to some visible point of the element.
    • x <number “Number”)>
    • y <number “Number”)>
    • modifiers <Array “Array”)<”Alt“|“Control”|”Meta“|“Shift”>> Modifier keys to press. Ensures that only these modifiers are pressed during the click, and then restores current modifiers back. If not specified, currently pressed modifiers are used.
    • force <boolean “Boolean”)> Whether to bypass the actionability checks. Defaults to false.
    • noWaitAfter <boolean “Boolean”)> Actions that initiate navigations are waiting for these navigations to happen and for pages to start loading. You can opt out of waiting via setting this flag. You would only need this option in the exceptional cases such as navigating to inaccessible pages. Defaults to false.
    • timeout <number “Number”)> Maximum time in milliseconds, defaults to 30 seconds, pass 0 to disable timeout. The default value can be changed by using the browserContext.setDefaultTimeout(timeout) or page.setDefaultTimeout(timeout) methods.
  • returns: <Promise “Promise”)> Promise which resolves when the element matching selector is successfully clicked. The Promise will be rejected if there is no element matching selector.

This method fetches an element with selector, scrolls it into view if needed, and then uses page.mouse to click in the center of the element. If there‘s no element matching selector, the method waits until a matching element appears in the DOM. If the element is detached during the actionability checks, the action is retried.

Shortcut for page.mainFrame().click(selector[, options]).

page.close([options])

  • options <Object “Object”)>
    • runBeforeUnload <boolean “Boolean”)> Defaults to false. Whether to run the before unload page handlers.
  • returns: <Promise “Promise”)>

By default, page.close() does not run beforeunload handlers.

NOTE if runBeforeUnload is passed as true, a beforeunload dialog might be summoned and should be handled manually via page‘s ’dialog’ event.

page.content()

Gets the full HTML contents of the page, including the doctype.

page.context()

  • returns: <BrowserContext>

Get the browser context that the page belongs to.

page.coverage

  • returns: <?ChromiumCoverage>

Browser-specific Coverage implementation, only available for Chromium atm. See ChromiumCoverage for more details.

page.dblclick(selector[, options])

  • selector <string “String”)> A selector to search for element to double click. If there are multiple elements satisfying the selector, the first will be double clicked. See working with selectors for more details.
  • options <Object “Object”)>
    • button <“left”|”right“|“middle”> Defaults to left.
    • delay <number “Number”)> Time to wait between mousedown and mouseup in milliseconds. Defaults to 0.
    • position <Object “Object”)> A point to double click relative to the top-left corner of element padding box. If not specified, double clicks to some visible point of the element.
    • x <number “Number”)>
    • y <number “Number”)>
    • modifiers <Array “Array”)<”Alt“|“Control”|”Meta“|“Shift”>> Modifier keys to press. Ensures that only these modifiers are pressed during the double click, and then restores current modifiers back. If not specified, currently pressed modifiers are used.
    • force <boolean “Boolean”)> Whether to bypass the actionability checks. Defaults to false.
    • noWaitAfter <boolean “Boolean”)> Actions that initiate navigations are waiting for these navigations to happen and for pages to start loading. You can opt out of waiting via setting this flag. You would only need this option in the exceptional cases such as navigating to inaccessible pages. Defaults to false.
    • timeout <number “Number”)> Maximum time in milliseconds, defaults to 30 seconds, pass 0 to disable timeout. The default value can be changed by using the browserContext.setDefaultTimeout(timeout) or page.setDefaultTimeout(timeout) methods.
  • returns: <Promise “Promise”)> Promise which resolves when the element matching selector is successfully double clicked. The Promise will be rejected if there is no element matching selector.

This method fetches an element with selector, scrolls it into view if needed, and then uses page.mouse to double click in the center of the element. If there‘s no element matching selector, the method waits until a matching element appears in the DOM. If the element is detached during the actionability checks, the action is retried.

Bear in mind that if the first click of the dblclick() triggers a navigation event, there will be an exception.

NOTE page.dblclick() dispatches two click events and a single dblclick event.

Shortcut for page.mainFrame().dblclick(selector[, options]).

page.dispatchEvent(selector, type[, eventInit, options])

  • selector <string “String”)> A selector to search for element to use. If there are multiple elements satisfying the selector, the first will be used. See working with selectors for more details.
  • type <string “String”)> DOM event type: "click", "dragstart", etc.
  • eventInit <Object “Object”)> event-specific initialization properties.
  • options <Object “Object”)>
    • timeout <number “Number”)> Maximum time in milliseconds, defaults to 30 seconds, pass 0 to disable timeout. The default value can be changed by using the browserContext.setDefaultTimeout(timeout) or page.setDefaultTimeout(timeout) methods.
  • returns: <Promise “Promise”)>

The snippet below dispatches the click event on the element. Regardless of the visibility state of the elment, click is dispatched. This is equivalend to calling element.click().

await page.dispatchEvent('button#submit', 'click');

Under the hood, it creates an instance of an event based on the given type, initializes it with eventInit properties and dispatches it on the element. Events are composed, cancelable and bubble by default.

Since eventInit is event-specific, please refer to the events documentation for the lists of initial properties:

You can also specify JSHandle as the property value if you want live objects to be passed into the event:

// Note you can only create DataTransfer in Chromium and Firefox
const dataTransfer = await page.evaluateHandle(() => new DataTransfer());
await page.dispatchEvent('#source', 'dragstart', { dataTransfer });

page.emulateMedia(options)

  • options <Object “Object”)>
    • media <“screen”|”print“> Changes the CSS media type of the page. The only allowed values are 'screen', 'print' and null. Passing null disables CSS media emulation.
    • colorScheme <“dark”|”light“|“no-preference”> Emulates 'prefers-colors-scheme' media feature, supported values are 'light', 'dark', 'no-preference'.
  • returns: <Promise “Promise”)>
await page.evaluate(() => matchMedia('screen').matches);
// → true
await page.evaluate(() => matchMedia('print').matches);
// → false

await page.emulateMedia({ media: 'print' });
await page.evaluate(() => matchMedia('screen').matches);
// → false
await page.evaluate(() => matchMedia('print').matches);
// → true

await page.emulateMedia({});
await page.evaluate(() => matchMedia('screen').matches);
// → true
await page.evaluate(() => matchMedia('print').matches);
// → false
``` ```
await page.emulateMedia({ colorScheme: 'dark' }] });
await page.evaluate(() => matchMedia('(prefers-color-scheme: dark)').matches);
// → true
await page.evaluate(() => matchMedia('(prefers-color-scheme: light)').matches);
// → false
await page.evaluate(() => matchMedia('(prefers-color-scheme: no-preference)').matches);
// → false

page.evaluate(pageFunction[, arg])

  • pageFunction <function “Function”)|string ”String“)> Function to be evaluated in the page context
  • arg <Serializable “Serializable”)|JSHandle> Optional argument to pass to pageFunction
  • returns: <Promise “Promise”)<Serializable ”Serializable“)>> Promise which resolves to the return value of pageFunction

If the function passed to the page.evaluate returns a Promise “Promise”), then page.evaluate would wait for the promise to resolve and return its value.

If the function passed to the page.evaluate returns a non-Serializable “Serializable”) value, then page.evaluate resolves to undefined. DevTools Protocol also supports transferring some additional values that are not serializable by JSON: -0, NaN, Infinity, -Infinity, and bigint literals.

Passing argument to pageFunction:

const result = await page.evaluate(([x, y]) => {
  return Promise.resolve(x * y);
}, [7, 8]);
console.log(result); // prints "56"

A string can also be passed in instead of a function:

console.log(await page.evaluate('1 + 2')); // prints "3"
const x = 10;
console.log(await page.evaluate(`1 + ${x}`)); // prints "11"

ElementHandle instances can be passed as an argument to the page.evaluate:

const bodyHandle = await page.$('body');
const html = await page.evaluate(([body, suffix]) => body.innerHTML + suffix, [bodyHandle, 'hello']);
await bodyHandle.dispose();

Shortcut for page.mainFrame().evaluate(pageFunction[, arg]).

page.evaluateHandle(pageFunction[, arg])

  • pageFunction <function “Function”)|string ”String“)> Function to be evaluated in the page context
  • arg <Serializable “Serializable”)|JSHandle> Optional argument to pass to pageFunction
  • returns: <Promise “Promise”)<JSHandle>> Promise which resolves to the return value of pageFunction as in-page object (JSHandle)

The only difference between page.evaluate and page.evaluateHandle is that page.evaluateHandle returns in-page object (JSHandle).

If the function passed to the page.evaluateHandle returns a Promise “Promise”), then page.evaluateHandle would wait for the promise to resolve and return its value.

A string can also be passed in instead of a function:

const aHandle = await page.evaluateHandle('document'); // Handle for the 'document'

JSHandle instances can be passed as an argument to the page.evaluateHandle:

const aHandle = await page.evaluateHandle(() => document.body);
const resultHandle = await page.evaluateHandle(body => body.innerHTML, aHandle);
console.log(await resultHandle.jsonValue());
await resultHandle.dispose();

page.exposeBinding(name, playwrightBinding)

  • name <string “String”)> Name of the function on the window object.
  • playwrightBinding <function “Function”)> Callback function that will be called in the Playwright‘s context.
  • returns: <Promise “Promise”)>

The method adds a function called name on the window object of every frame in this page. When called, the function executes playwrightBinding in Node.js and returns a Promise “Promise”) which resolves to the return value of playwrightBinding. If the playwrightBinding returns a Promise ”Promise“), it will be awaited.

The first argument of the playwrightBinding function contains information about the caller: { browserContext: BrowserContext, page: Page, frame: Frame }.

See browserContext.exposeBinding(name, playwrightBinding) for the context-wide version.

NOTE Functions installed via page.exposeBinding survive navigations.

An example of exposing page URL to all frames in a page:

const { webkit } = require('playwright');  // Or 'chromium' or 'firefox'.

(async () => {
  const browser = await webkit.launch({ headless: false });
  const context = await browser.newContext();
  const page = await context.newPage();
  await page.exposeBinding('pageURL', ({ page }) => page.url());
  await page.setContent(`
    <script>
      async function onClick() {
        document.querySelector('div').textContent = await window.pageURL();
      }
    </script>
    <button onclick="onClick()">Click me</button>
    <div></div>
  `);
  await page.click('button');
})();

page.exposeFunction(name, playwrightFunction)

  • name <string “String”)> Name of the function on the window object
  • playwrightFunction <function “Function”)> Callback function which will be called in Playwright‘s context.
  • returns: <Promise “Promise”)>

The method adds a function called name on the window object of every frame in the page. When called, the function executes playwrightFunction in Node.js and returns a Promise “Promise”) which resolves to the return value of playwrightFunction.

If the playwrightFunction returns a Promise “Promise”), it will be awaited.

See browserContext.exposeFunction(name, playwrightFunction) for context-wide exposed function.

NOTE Functions installed via page.exposeFunction survive navigations.

An example of adding an md5 function to the page:

const { webkit } = require('playwright');  // Or 'chromium' or 'firefox'.
const crypto = require('crypto');

(async () => {
  const browser = await webkit.launch({ headless: false });
  const page = await browser.newPage();
  await page.exposeFunction('md5', text => crypto.createHash('md5').update(text).digest('hex'));
  await page.setContent(`
    <script>
      async function onClick() {
        document.querySelector('div').textContent = await window.md5('PLAYWRIGHT');
      }
    </script>
    <button onclick="onClick()">Click me</button>
    <div></div>
  `);
  await page.click('button');
})();

An example of adding a window.readfile function to the page:

const { chromium } = require('playwright');  // Or 'firefox' or 'webkit'.
const fs = require('fs');

(async () => {
  const browser = await chromium.launch();
  const page = await browser.newPage();
  page.on('console', msg => console.log(msg.text()));
  await page.exposeFunction('readfile', async filePath => {
    return new Promise((resolve, reject) => {
      fs.readFile(filePath, 'utf8', (err, text) => {
        if (err)
          reject(err);
        else
          resolve(text);
      });
    });
  });
  await page.evaluate(async () => {
    // use window.readfile to read contents of a file
    const content = await window.readfile('/etc/hosts');
    console.log(content);
  });
  await browser.close();
})();

page.fill(selector, value[, options])

  • selector <string “String”)> A selector to query page for. See working with selectors for more details.
  • value <string “String”)> Value to fill for the <input>, <textarea> or [contenteditable] element.
  • options <Object “Object”)>
    • noWaitAfter <boolean “Boolean”)> Actions that initiate navigations are waiting for these navigations to happen and for pages to start loading. You can opt out of waiting via setting this flag. You would only need this option in the exceptional cases such as navigating to inaccessible pages. Defaults to false.
    • timeout <number “Number”)> Maximum time in milliseconds, defaults to 30 seconds, pass 0 to disable timeout. The default value can be changed by using the browserContext.setDefaultTimeout(timeout) or page.setDefaultTimeout(timeout) methods.
  • returns: <Promise “Promise”)>

This method waits for an element matching selector, waits for actionability checks, focuses the element, fills it and triggers an input event after filling. If the element matching selector is not an <input>, <textarea> or [contenteditable] element, this method throws an error. Note that you can pass an empty string to clear the input field.

To send fine-grained keyboard events, use page.type.

Shortcut for page.mainFrame().fill()

page.focus(selector[, options])

  • selector <string “String”)> A selector of an element to focus. If there are multiple elements satisfying the selector, the first will be focused. See working with selectors for more details.
  • options <Object “Object”)>
    • timeout <number “Number”)> Maximum time in milliseconds, defaults to 30 seconds, pass 0 to disable timeout. The default value can be changed by using the browserContext.setDefaultTimeout(timeout) or page.setDefaultTimeout(timeout) methods.
  • returns: <Promise “Promise”)> Promise which resolves when the element matching selector is successfully focused. The promise will be rejected if there is no element matching selector.

This method fetches an element with selector and focuses it. If there‘s no element matching selector, the method waits until a matching element a

(本文超出站点单文档体积上限,已截断)