Skip to content

Latest commit

 

History

History
607 lines (394 loc) · 24.3 KB

class-elementhandle.md

File metadata and controls

607 lines (394 loc) · 24.3 KB

class: ElementHandle

  • extends: [JSHandle]

ElementHandle represents an in-page DOM element. ElementHandles can be created with the [method: Page.$] method.

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

(async () => {
  const browser = await chromium.launch();
  const page = await browser.newPage();
  await page.goto('https://example.com');
  const hrefElement = await page.$('a');
  await hrefElement.click();
  // ...
})();

ElementHandle prevents DOM element from garbage collection unless the handle is disposed with [method: JSHandle.dispose]. ElementHandles are auto-disposed when their origin frame gets navigated.

ElementHandle instances can be used as an argument in [method: Page.$eval] and [method: Page.evaluate] methods.

async method: ElementHandle.$

  • returns: <[null]|[ElementHandle]>

The method finds an element matching the specified selector in the ElementHandle's subtree. See Working with selectors for more details. If no elements match the selector, returns null.

param: ElementHandle.$.selector = %%-query-selector-%%

async method: ElementHandle.$$

  • returns: <[Array]<[ElementHandle]>>

The method finds all elements matching the specified selector in the ElementHandles subtree. See Working with selectors for more details. If no elements match the selector, returns empty array.

param: ElementHandle.$$.selector = %%-query-selector-%%

async method: ElementHandle.$eval

  • returns: <[Serializable]>

Returns the return value of [param: pageFunction]

The method finds an element matching the specified selector in the ElementHandles subtree and passes it as a first argument to [param: pageFunction]. See Working with selectors for more details. If no elements match the selector, the method throws an error.

If [param: pageFunction] returns a [Promise], then frame.$eval would wait for the promise to resolve and return its value.

Examples:

const tweetHandle = await page.$('.tweet');
expect(await tweetHandle.$eval('.like', node => node.innerText)).toBe('100');
expect(await tweetHandle.$eval('.retweets', node => node.innerText)).toBe('10');

param: ElementHandle.$eval.selector = %%-query-selector-%%

param: ElementHandle.$eval.pageFunction

  • pageFunction <[function]([Element])>

Function to be evaluated in browser context

param: ElementHandle.$eval.arg

  • arg <[EvaluationArgument]>

Optional argument to pass to [param: pageFunction]

async method: ElementHandle.$$eval

  • returns: <[Serializable]>

Returns the return value of [param: pageFunction]

The method finds all elements matching the specified selector in the ElementHandle's subtree and passes an array of matched elements as a first argument to [param: pageFunction]. See Working with selectors for more details.

If [param: pageFunction] returns a [Promise], then frame.$$eval would wait for the promise to resolve and return its value.

Examples:

<div class="feed">
  <div class="tweet">Hello!</div>
  <div class="tweet">Hi!</div>
</div>
const feedHandle = await page.$('.feed');
expect(await feedHandle.$$eval('.tweet', nodes => nodes.map(n => n.innerText))).toEqual(['Hello!', 'Hi!']);

param: ElementHandle.$$eval.selector = %%-query-selector-%%

param: ElementHandle.$$eval.pageFunction

  • pageFunction <[function]([Array]<[Element]>)>

Function to be evaluated in browser context

param: ElementHandle.$$eval.arg

  • arg <[EvaluationArgument]>

Optional argument to pass to [param: pageFunction]

async method: ElementHandle.boundingBox

  • returns: <[null]|[Object]>
    • x <[float]> the x coordinate of the element in pixels.
    • y <[float]> the y coordinate of the element in pixels.
    • width <[float]> the width of the element in pixels.
    • height <[float]> the height of the element in pixels.

This method returns the bounding box of the element, or null if the element is not visible. The bounding box is calculated relative to the main frame viewport - which is usually the same as the browser window.

Scrolling affects the returned bonding box, similarly to Element.getBoundingClientRect. That means x and/or y may be negative.

Elements from child frames return the bounding box relative to the main frame, unlike the Element.getBoundingClientRect.

Assuming the page is static, it is safe to use bounding box coordinates to perform input. For example, the following snippet should click the center of the element.

const box = await elementHandle.boundingBox();
await page.mouse.click(box.x + box.width / 2, box.y + box.height / 2);

async method: ElementHandle.check

This method checks the element by performing the following steps:

  1. Ensure that element is a checkbox or a radio input. If not, this method rejects. If the element is already checked, this method returns immediately.
  2. Wait for actionability checks on the element, unless [option: force] option is set.
  3. Scroll the element into view if needed.
  4. Use [property: Page.mouse] to click in the center of the element.
  5. Wait for initiated navigations to either succeed or fail, unless [option: noWaitAfter] option is set.
  6. Ensure that the element is now checked. If not, this method rejects.

If the element is detached from the DOM at any moment during the action, this method rejects.

When all steps combined have not finished during the specified [option: timeout], this method rejects with a [TimeoutError]. Passing zero timeout disables this.

option: ElementHandle.check.force = %%-input-force-%%

option: ElementHandle.check.noWaitAfter = %%-input-no-wait-after-%%

option: ElementHandle.check.timeout = %%-input-timeout-%%

async method: ElementHandle.click

This method clicks the element by performing the following steps:

  1. Wait for actionability checks on the element, unless [option: force] option is set.
  2. Scroll the element into view if needed.
  3. Use [property: Page.mouse] to click in the center of the element, or the specified [option: position].
  4. Wait for initiated navigations to either succeed or fail, unless [option: noWaitAfter] option is set.

If the element is detached from the DOM at any moment during the action, this method rejects.

When all steps combined have not finished during the specified [option: timeout], this method rejects with a [TimeoutError]. Passing zero timeout disables this.

option: ElementHandle.click.button = %%-input-button-%%

option: ElementHandle.click.clickCount = %%-input-click-count-%%

option: ElementHandle.click.delay = %%-input-down-up-delay-%%

option: ElementHandle.click.position = %%-input-position-%%

option: ElementHandle.click.modifiers = %%-input-modifiers-%%

option: ElementHandle.click.force = %%-input-force-%%

option: ElementHandle.click.noWaitAfter = %%-input-no-wait-after-%%

option: ElementHandle.click.timeout = %%-input-timeout-%%

async method: ElementHandle.contentFrame

  • returns: <[null]|[Frame]>

Returns the content frame for element handles referencing iframe nodes, or null otherwise

async method: ElementHandle.dblclick

This method double clicks the element by performing the following steps:

  1. Wait for actionability checks on the element, unless [option: force] option is set.
  2. Scroll the element into view if needed.
  3. Use [property: Page.mouse] to double click in the center of the element, or the specified [option: position].
  4. Wait for initiated navigations to either succeed or fail, unless [option: noWaitAfter] option is set. Note that if the first click of the dblclick() triggers a navigation event, this method will reject.

If the element is detached from the DOM at any moment during the action, this method rejects.

When all steps combined have not finished during the specified [option: timeout], this method rejects with a [TimeoutError]. Passing zero timeout disables this.

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

option: ElementHandle.dblclick.button = %%-input-button-%%

option: ElementHandle.dblclick.delay = %%-input-down-up-delay-%%

option: ElementHandle.dblclick.position = %%-input-position-%%

option: ElementHandle.dblclick.modifiers = %%-input-modifiers-%%

option: ElementHandle.dblclick.force = %%-input-force-%%

option: ElementHandle.dblclick.noWaitAfter = %%-input-no-wait-after-%%

option: ElementHandle.dblclick.timeout = %%-input-timeout-%%

async method: ElementHandle.dispatchEvent

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 elementHandle.dispatchEvent('click');

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

Since [param: 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 elementHandle.dispatchEvent('dragstart', { dataTransfer });

param: ElementHandle.dispatchEvent.type

  • type <[string]>

DOM event type: "click", "dragstart", etc.

param: ElementHandle.dispatchEvent.eventInit

  • eventInit <[EvaluationArgument]>

Optional event-specific initialization properties.

async method: ElementHandle.fill

This method waits for actionability checks, focuses the element, fills it and triggers an input event after filling. If the element 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.

param: ElementHandle.fill.value

  • value <[string]>

Value to set for the <input>, <textarea> or [contenteditable] element.

option: ElementHandle.fill.noWaitAfter = %%-input-no-wait-after-%%

option: ElementHandle.fill.timeout = %%-input-timeout-%%

async method: ElementHandle.focus

Calls focus on the element.

async method: ElementHandle.getAttribute

  • returns: <[null]|[string]>

Returns element attribute value.

param: ElementHandle.getAttribute.name

  • name <[string]>

Attribute name to get the value for.

async method: ElementHandle.hover

This method hovers over the element by performing the following steps:

  1. Wait for actionability checks on the element, unless [option: force] option is set.
  2. Scroll the element into view if needed.
  3. Use [property: Page.mouse] to hover over the center of the element, or the specified [option: position].
  4. Wait for initiated navigations to either succeed or fail, unless noWaitAfter option is set.

If the element is detached from the DOM at any moment during the action, this method rejects.

When all steps combined have not finished during the specified [option: timeout], this method rejects with a [TimeoutError]. Passing zero timeout disables this.

option: ElementHandle.hover.position = %%-input-position-%%

option: ElementHandle.hover.modifiers = %%-input-modifiers-%%

option: ElementHandle.hover.force = %%-input-force-%%

option: ElementHandle.hover.timeout = %%-input-timeout-%%

async method: ElementHandle.innerHTML

  • returns: <[string]>

Returns the element.innerHTML.

async method: ElementHandle.innerText

  • returns: <[string]>

Returns the element.innerText.

async method: ElementHandle.isDisabled

  • returns: <[boolean]>

Returns whether the element is disabled, the opposite of enabled.

async method: ElementHandle.isEditable

  • returns: <[boolean]>

Returns whether the element is editable.

async method: ElementHandle.isEnabled

  • returns: <[boolean]>

Returns whether the element is enabled.

async method: ElementHandle.isHidden

  • returns: <[boolean]>

Returns whether the element is hidden, the opposite of visible.

async method: ElementHandle.isVisible

  • returns: <[boolean]>

Returns whether the element is visible.

async method: ElementHandle.ownerFrame

  • returns: <[null]|[Frame]>

Returns the frame containing the given element.

async method: ElementHandle.press

Focuses the element, and then uses [method: Keyboard.down] and [method: Keyboard.up].

[param: key] can specify the intended keyboardEvent.key value or a single character to generate the text for. A superset of the [param: key] values can be found here. Examples of the keys are:

F1 - F12, Digit0- Digit9, KeyA- KeyZ, Backquote, Minus, Equal, Backslash, Backspace, Tab, Delete, Escape, ArrowDown, End, Enter, Home, Insert, PageDown, PageUp, ArrowRight, ArrowUp, etc.

Following modification shortcuts are also supported: Shift, Control, Alt, Meta, ShiftLeft.

Holding down Shift will type the text that corresponds to the [param: key] in the upper case.

If [param: key] is a single character, it is case-sensitive, so the values a and A will generate different respective texts.

Shortcuts such as key: "Control+o" or key: "Control+Shift+T" are supported as well. When speficied with the modifier, modifier is pressed and being held while the subsequent key is being pressed.

param: ElementHandle.press.key

  • key <[string]>

Name of the key to press or a character to generate, such as ArrowLeft or a.

option: ElementHandle.press.delay

  • delay <[float]>

Time to wait between keydown and keyup in milliseconds. Defaults to 0.

option: ElementHandle.press.noWaitAfter = %%-input-no-wait-after-%%

option: ElementHandle.press.timeout = %%-input-timeout-%%

async method: ElementHandle.screenshot

  • returns: <[Buffer]>

Returns the buffer with the captured screenshot.

This method waits for the actionability checks, then scrolls element into view before taking a screenshot. If the element is detached from DOM, the method throws an error.

option: ElementHandle.screenshot.path

  • path <[path]>

The file path to save the image to. The screenshot type will be inferred from file extension. If [option: path] is a relative path, then it is resolved relative to the current working directory. If no path is provided, the image won't be saved to the disk.

option: ElementHandle.screenshot.type

  • type <"png"|"jpeg">

Specify screenshot type, defaults to png.

option: ElementHandle.screenshot.quality

  • quality <[int]>

The quality of the image, between 0-100. Not applicable to png images.

option: ElementHandle.screenshot.omitBackground

  • omitBackground <[boolean]>

Hides default white background and allows capturing screenshots with transparency. Not applicable to jpeg images. Defaults to false.

option: ElementHandle.screenshot.timeout = %%-input-timeout-%%

async method: ElementHandle.scrollIntoViewIfNeeded

This method waits for actionability checks, then tries to scroll element into view, unless it is completely visible as defined by IntersectionObserver's ratio.

Throws when elementHandle does not point to an element connected to a Document or a ShadowRoot.

option: ElementHandle.scrollIntoViewIfNeeded.timeout = %%-input-timeout-%%

async method: ElementHandle.selectOption

  • returns: <[Array]<[string]>>

Returns the array of option values that have been successfully selected.

Triggers a change and input event once all the provided options have been selected. If element is not a <select> element, the method throws an error.

// single selection matching the value
handle.selectOption('blue');

// single selection matching both the value and the label
handle.selectOption({ label: 'Blue' });

// multiple selection
handle.selectOption('red', 'green', 'blue');

// multiple selection for blue, red and second option
handle.selectOption({ value: 'blue' }, { index: 2 }, 'red');

param: ElementHandle.selectOption.values = %%-select-options-values-%%

option: ElementHandle.selectOption.noWaitAfter = %%-input-no-wait-after-%%

option: ElementHandle.selectOption.timeout = %%-input-timeout-%%

async method: ElementHandle.selectText

This method waits for actionability checks, then focuses the element and selects all its text content.

option: ElementHandle.selectText.timeout = %%-input-timeout-%%

async method: ElementHandle.setInputFiles

This method expects elementHandle to point to an input element.

Sets the value of the file input to these file paths or files. If some of the filePaths are relative paths, then they are resolved relative to the the current working directory. For empty array, clears the selected files.

param: ElementHandle.setInputFiles.files = %%-input-files-%%

option: ElementHandle.setInputFiles.noWaitAfter = %%-input-no-wait-after-%%

option: ElementHandle.setInputFiles.timeout = %%-input-timeout-%%

async method: ElementHandle.tap

This method taps the element by performing the following steps:

  1. Wait for actionability checks on the element, unless [option: force] option is set.
  2. Scroll the element into view if needed.
  3. Use [property: Page.touchscreen] to tap the center of the element, or the specified [option: position].
  4. Wait for initiated navigations to either succeed or fail, unless [option: noWaitAfter] option is set.

If the element is detached from the DOM at any moment during the action, this method rejects.

When all steps combined have not finished during the specified [option: timeout], this method rejects with a [TimeoutError]. Passing zero timeout disables this.

NOTE elementHandle.tap() requires that the hasTouch option of the browser context be set to true.

option: ElementHandle.tap.position = %%-input-position-%%

option: ElementHandle.tap.modifiers = %%-input-modifiers-%%

option: ElementHandle.tap.force = %%-input-force-%%

option: ElementHandle.tap.noWaitAfter = %%-input-no-wait-after-%%

option: ElementHandle.tap.timeout = %%-input-timeout-%%

async method: ElementHandle.textContent

  • returns: <[null]|[string]>

Returns the node.textContent.

async method: ElementHandle.type

Focuses the element, and then sends a keydown, keypress/input, and keyup event for each character in the text.

To press a special key, like Control or ArrowDown, use [method: ElementHandle.press].

await elementHandle.type('Hello'); // Types instantly
await elementHandle.type('World', {delay: 100}); // Types slower, like a user

An example of typing into a text field and then submitting the form:

const elementHandle = await page.$('input');
await elementHandle.type('some text');
await elementHandle.press('Enter');

param: ElementHandle.type.text

  • text <[string]>

A text to type into a focused element.

option: ElementHandle.type.delay

  • delay <[float]>

Time to wait between key presses in milliseconds. Defaults to 0.

option: ElementHandle.type.noWaitAfter = %%-input-no-wait-after-%%

option: ElementHandle.type.timeout = %%-input-timeout-%%

async method: ElementHandle.uncheck

This method checks the element by performing the following steps:

  1. Ensure that element is a checkbox or a radio input. If not, this method rejects. If the element is already unchecked, this method returns immediately.
  2. Wait for actionability checks on the element, unless [option: force] option is set.
  3. Scroll the element into view if needed.
  4. Use [property: Page.mouse] to click in the center of the element.
  5. Wait for initiated navigations to either succeed or fail, unless [option: noWaitAfter] option is set.
  6. Ensure that the element is now unchecked. If not, this method rejects.

If the element is detached from the DOM at any moment during the action, this method rejects.

When all steps combined have not finished during the specified [option: timeout], this method rejects with a [TimeoutError]. Passing zero timeout disables this.

option: ElementHandle.uncheck.force = %%-input-force-%%

option: ElementHandle.uncheck.noWaitAfter = %%-input-no-wait-after-%%

option: ElementHandle.uncheck.timeout = %%-input-timeout-%%

async method: ElementHandle.waitForElementState

Returns when the element satisfies the [param: state].

Depending on the [param: state] parameter, this method waits for one of the actionability checks to pass. This method throws when the element is detached while waiting, unless waiting for the "hidden" state.

  • "visible" Wait until the element is visible.
  • "hidden" Wait until the element is not visible or not attached. Note that waiting for hidden does not throw when the element detaches.
  • "stable" Wait until the element is both visible and stable.
  • "enabled" Wait until the element is enabled.
  • "disabled" Wait until the element is not enabled.
  • "editable" Wait until the element is editable.

If the element does not satisfy the condition for the [option: timeout] milliseconds, this method will throw.

param: ElementHandle.waitForElementState.state

  • state <"visible"|"hidden"|"stable"|"enabled"|"disabled"|"editable">

A state to wait for, see below for more details.

option: ElementHandle.waitForElementState.timeout = %%-input-timeout-%%

async method: ElementHandle.waitForSelector

  • returns: <[null]|[ElementHandle]>

Returns element specified by selector when it satisfies [option: state] option. Returns null if waiting for hidden or detached.

Wait for the [param: selector] relative to the element handle to satisfy [option: state] option (either appear/disappear from dom, or become visible/hidden). If at the moment of calling the method [param: selector] already satisfies the condition, the method will return immediately. If the selector doesn't satisfy the condition for the [option: timeout] milliseconds, the function will throw.

await page.setContent(`<div><span></span></div>`);
const div = await page.$('div');
// Waiting for the 'span' selector relative to the div.
const span = await div.waitForSelector('span', { state: 'attached' });

NOTE This method does not work across navigations, use [method: Page.waitForSelector] instead.

param: ElementHandle.waitForSelector.selector = %%-query-selector-%%

option: ElementHandle.waitForSelector.state = %%-wait-for-selector-state-%%

option: ElementHandle.waitForSelector.timeout = %%-input-timeout-%%