feat: implement Locators (#10305)

This commit is contained in:
Alex Rudenko 2023-06-02 19:46:10 +02:00 committed by GitHub
parent e8d044cb8d
commit 1f978f5fc5
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
30 changed files with 716 additions and 20 deletions

View File

@ -29,6 +29,7 @@ sidebar_label: API
| [JSCoverage](./puppeteer.jscoverage.md) | |
| [JSHandle](./puppeteer.jshandle.md) | <p>Represents a reference to a JavaScript object. Instances can be created using [Page.evaluateHandle()](./puppeteer.page.evaluatehandle.md).</p><p>Handles prevent the referenced JavaScript object from being garbage-collected unless the handle is purposely [disposed](./puppeteer.jshandle.dispose.md). JSHandles are auto-disposed when their associated frame is navigated away or the parent context gets destroyed.</p><p>Handles can be used as arguments for any evaluation function such as [Page.$eval()](./puppeteer.page._eval.md), [Page.evaluate()](./puppeteer.page.evaluate.md), and [Page.evaluateHandle()](./puppeteer.page.evaluatehandle.md). They are resolved to their referenced object.</p> |
| [Keyboard](./puppeteer.keyboard.md) | Keyboard provides an api for managing a virtual keyboard. The high level api is [Keyboard.type()](./puppeteer.keyboard.type.md), which takes raw characters and generates proper keydown, keypress/input, and keyup events on your page. |
| [Locator](./puppeteer.locator.md) | Locators describe a strategy of locating elements and performing an action on them. If the action fails because the element is not ready for the action, the whole operation is retried. Various preconditions for a successful action are checked automatically. |
| [Mouse](./puppeteer.mouse.md) | The Mouse class operates in main-frame CSS pixels relative to the top-left corner of the viewport. |
| [Page](./puppeteer.page.md) | <p>Page provides methods to interact with a single tab or [extension background page](https://developer.chrome.com/extensions/background_pages) in the browser.</p><p>:::note</p><p>One Browser instance might have multiple Page instances.</p><p>:::</p> |
| [ProductLauncher](./puppeteer.productlauncher.md) | Describes a launcher - a class that is able to create and launch a browser instance. |
@ -49,6 +50,7 @@ sidebar_label: API
| [BrowserContextEmittedEvents](./puppeteer.browsercontextemittedevents.md) | |
| [BrowserEmittedEvents](./puppeteer.browseremittedevents.md) | All the events a [browser instance](./puppeteer.browser.md) may emit. |
| [InterceptResolutionAction](./puppeteer.interceptresolutionaction.md) | |
| [LocatorEmittedEvents](./puppeteer.locatoremittedevents.md) | All the events that a locator instance may emit. |
| [PageEmittedEvents](./puppeteer.pageemittedevents.md) | All the events that a page instance may emit. |
## Functions
@ -64,6 +66,7 @@ sidebar_label: API
| Interface | Description |
| --------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| [ActionOptions](./puppeteer.actionoptions.md) | |
| [BoundingBox](./puppeteer.boundingbox.md) | |
| [BoxModel](./puppeteer.boxmodel.md) | |
| [BrowserConnectOptions](./puppeteer.browserconnectoptions.md) | Generic browser options that can be passed when launching any browser or when connecting to an existing browser instance. |
@ -91,6 +94,8 @@ sidebar_label: API
| [JSCoverageEntry](./puppeteer.jscoverageentry.md) | The CoverageEntry class for JavaScript |
| [JSCoverageOptions](./puppeteer.jscoverageoptions.md) | Set of configurable options for JS coverage. |
| [LaunchOptions](./puppeteer.launchoptions.md) | Generic launch options that can be passed when launching any browser. |
| [LocatorEventObject](./puppeteer.locatoreventobject.md) | |
| [LocatorOptions](./puppeteer.locatoroptions.md) | |
| [MediaFeature](./puppeteer.mediafeature.md) | |
| [Metrics](./puppeteer.metrics.md) | |
| [MouseClickOptions](./puppeteer.mouseclickoptions.md) | |
@ -142,6 +147,7 @@ sidebar_label: API
| Type Alias | Description |
| ------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------- |
| [ActionCondition](./puppeteer.actioncondition.md) | |
| [ActionResult](./puppeteer.actionresult.md) | |
| [Awaitable](./puppeteer.awaitable.md) | |
| [AwaitableIterable](./puppeteer.awaitableiterable.md) | |
@ -171,3 +177,4 @@ sidebar_label: API
| [PuppeteerNodeLaunchOptions](./puppeteer.puppeteernodelaunchoptions.md) | Utility type exposed to enable users to define options that can be passed to <code>puppeteer.launch</code> without having to list the set of all types. |
| [ResourceType](./puppeteer.resourcetype.md) | Resource types for HTTPRequests as perceived by the rendering engine. |
| [TargetFilterCallback](./puppeteer.targetfiltercallback.md) | |
| [VisibilityOption](./puppeteer.visibilityoption.md) | |

View File

@ -0,0 +1,16 @@
---
sidebar_label: ActionCondition
---
# ActionCondition type
#### Signature:
```typescript
export type ActionCondition = (
element: ElementHandle,
signal: AbortSignal
) => Promise<void>;
```
**References:** [ElementHandle](./puppeteer.elementhandle.md)

View File

@ -0,0 +1,18 @@
---
sidebar_label: ActionOptions
---
# ActionOptions interface
#### Signature:
```typescript
export interface ActionOptions
```
## Properties
| Property | Modifiers | Type | Description | Default |
| ---------- | --------------------- | ----------------------------------------------------- | ----------- | ------- |
| conditions | | [ActionCondition](./puppeteer.actioncondition.md)\[\] | | |
| signal | <code>optional</code> | AbortSignal | | |

View File

@ -0,0 +1,29 @@
---
sidebar_label: Frame.locator
---
# Frame.locator() method
Creates a locator for the provided `selector`. See [Locator](./puppeteer.locator.md) for details and supported actions.
#### Signature:
```typescript
class Frame {
locator(selector: string): Locator;
}
```
## Parameters
| Parameter | Type | Description |
| --------- | ------ | ----------- |
| selector | string | |
**Returns:**
[Locator](./puppeteer.locator.md)
## Remarks
Locators API is experimental and we will not follow semver for breaking change in the Locators API.

View File

@ -81,6 +81,7 @@ console.log(text);
| [hover(selector)](./puppeteer.frame.hover.md) | | Hovers the pointer over the center of the first element that matches the <code>selector</code>. |
| [isDetached()](./puppeteer.frame.isdetached.md) | | Is<code>true</code> if the frame has been detached. Otherwise, <code>false</code>. |
| [isOOPFrame()](./puppeteer.frame.isoopframe.md) | | Is <code>true</code> if the frame is an out-of-process (OOP) frame. Otherwise, <code>false</code>. |
| [locator(selector)](./puppeteer.frame.locator.md) | | Creates a locator for the provided <code>selector</code>. See [Locator](./puppeteer.locator.md) for details and supported actions. |
| [name()](./puppeteer.frame.name.md) | | The frame's <code>name</code> attribute as specified in the tag. |
| [page()](./puppeteer.frame.page.md) | | The page associated with the frame. |
| [parentFrame()](./puppeteer.frame.parentframe.md) | | The parent frame, if any. Detached and main frames return <code>null</code>. |

View File

@ -0,0 +1,27 @@
---
sidebar_label: Locator.(constructor)
---
# Locator.(constructor)
Constructs a new instance of the `Locator` class
#### Signature:
```typescript
class Locator {
constructor(
pageOrFrame: Page | Frame,
selector: string,
options?: LocatorOptions
);
}
```
## Parameters
| Parameter | Type | Description |
| ----------- | ------------------------------------------------------------ | ------------ |
| pageOrFrame | [Page](./puppeteer.page.md) \| [Frame](./puppeteer.frame.md) | |
| selector | string | |
| options | [LocatorOptions](./puppeteer.locatoroptions.md) | _(Optional)_ |

View File

@ -0,0 +1,27 @@
---
sidebar_label: Locator.click
---
# Locator.click() method
#### Signature:
```typescript
class Locator {
click(
clickOptions?: ClickOptions & {
signal?: AbortSignal;
}
): Promise<void>;
}
```
## Parameters
| Parameter | Type | Description |
| ------------ | --------------------------------------------------------------------------- | ------------ |
| clickOptions | [ClickOptions](./puppeteer.clickoptions.md) &amp; { signal?: AbortSignal; } | _(Optional)_ |
**Returns:**
Promise&lt;void&gt;

View File

@ -0,0 +1,31 @@
---
sidebar_label: Locator.fill
---
# Locator.fill() method
Fills out the input identified by the locator using the provided value. The type of the input is determined at runtime and the appropriate fill-out method is chosen based on the type. contenteditable, selector, inputs are supported.
#### Signature:
```typescript
class Locator {
fill(
value: string,
fillOptions?: {
signal?: AbortSignal;
}
): Promise<void>;
}
```
## Parameters
| Parameter | Type | Description |
| ----------- | ------------------------- | ------------ |
| value | string | |
| fillOptions | { signal?: AbortSignal; } | _(Optional)_ |
**Returns:**
Promise&lt;void&gt;

View File

@ -0,0 +1,23 @@
---
sidebar_label: Locator.hover
---
# Locator.hover() method
#### Signature:
```typescript
class Locator {
hover(hoverOptions?: {signal?: AbortSignal}): Promise<void>;
}
```
## Parameters
| Parameter | Type | Description |
| ------------ | ------------------------- | ------------ |
| hoverOptions | { signal?: AbortSignal; } | _(Optional)_ |
**Returns:**
Promise&lt;void&gt;

View File

@ -0,0 +1,38 @@
---
sidebar_label: Locator
---
# Locator class
Locators describe a strategy of locating elements and performing an action on them. If the action fails because the element is not ready for the action, the whole operation is retried. Various preconditions for a successful action are checked automatically.
#### Signature:
```typescript
export declare class Locator extends EventEmitter
```
**Extends:** [EventEmitter](./puppeteer.eventemitter.md)
## Constructors
| Constructor | Modifiers | Description |
| ------------------------------------------------------------------------------------- | --------- | ----------------------------------------------------------- |
| [(constructor)(pageOrFrame, selector, options)](./puppeteer.locator._constructor_.md) | | Constructs a new instance of the <code>Locator</code> class |
## Methods
| Method | Modifiers | Description |
| ------------------------------------------------------------------------------------------------ | --------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| [click(clickOptions)](./puppeteer.locator.click.md) | | |
| [fill(value, fillOptions)](./puppeteer.locator.fill.md) | | Fills out the input identified by the locator using the provided value. The type of the input is determined at runtime and the appropriate fill-out method is chosen based on the type. contenteditable, selector, inputs are supported. |
| [hover(hoverOptions)](./puppeteer.locator.hover.md) | | |
| [off(eventName, handler)](./puppeteer.locator.off.md) | | |
| [on(eventName, handler)](./puppeteer.locator.on.md) | | |
| [once(eventName, handler)](./puppeteer.locator.once.md) | | |
| [scroll(scrollOptions)](./puppeteer.locator.scroll.md) | | |
| [setEnsureElementIsInTheViewport(value)](./puppeteer.locator.setensureelementisintheviewport.md) | | |
| [setTimeout(timeout)](./puppeteer.locator.settimeout.md) | | |
| [setVisibility(visibility)](./puppeteer.locator.setvisibility.md) | | |
| [setWaitForEnabled(value)](./puppeteer.locator.setwaitforenabled.md) | | |
| [setWaitForStableBoundingBox(value)](./puppeteer.locator.setwaitforstableboundingbox.md) | | |

View File

@ -0,0 +1,27 @@
---
sidebar_label: Locator.off
---
# Locator.off() method
#### Signature:
```typescript
class Locator {
off<K extends keyof LocatorEventObject>(
eventName: K,
handler: (event: LocatorEventObject[K]) => void
): this;
}
```
## Parameters
| Parameter | Type | Description |
| --------- | -------------------------------------------------------------------------------- | ----------- |
| eventName | K | |
| handler | (event: [LocatorEventObject](./puppeteer.locatoreventobject.md)\[K\]) =&gt; void | |
**Returns:**
this

View File

@ -0,0 +1,27 @@
---
sidebar_label: Locator.on
---
# Locator.on() method
#### Signature:
```typescript
class Locator {
on<K extends keyof LocatorEventObject>(
eventName: K,
handler: (event: LocatorEventObject[K]) => void
): this;
}
```
## Parameters
| Parameter | Type | Description |
| --------- | -------------------------------------------------------------------------------- | ----------- |
| eventName | K | |
| handler | (event: [LocatorEventObject](./puppeteer.locatoreventobject.md)\[K\]) =&gt; void | |
**Returns:**
this

View File

@ -0,0 +1,27 @@
---
sidebar_label: Locator.once
---
# Locator.once() method
#### Signature:
```typescript
class Locator {
once<K extends keyof LocatorEventObject>(
eventName: K,
handler: (event: LocatorEventObject[K]) => void
): this;
}
```
## Parameters
| Parameter | Type | Description |
| --------- | -------------------------------------------------------------------------------- | ----------- |
| eventName | K | |
| handler | (event: [LocatorEventObject](./puppeteer.locatoreventobject.md)\[K\]) =&gt; void | |
**Returns:**
this

View File

@ -0,0 +1,27 @@
---
sidebar_label: Locator.scroll
---
# Locator.scroll() method
#### Signature:
```typescript
class Locator {
scroll(scrollOptions?: {
scrollTop?: number;
scrollLeft?: number;
signal?: AbortSignal;
}): Promise<void>;
}
```
## Parameters
| Parameter | Type | Description |
| ------------- | ------------------------------------------------------------------ | ------------ |
| scrollOptions | { scrollTop?: number; scrollLeft?: number; signal?: AbortSignal; } | _(Optional)_ |
**Returns:**
Promise&lt;void&gt;

View File

@ -0,0 +1,23 @@
---
sidebar_label: Locator.setEnsureElementIsInTheViewport
---
# Locator.setEnsureElementIsInTheViewport() method
#### Signature:
```typescript
class Locator {
setEnsureElementIsInTheViewport(value: boolean): this;
}
```
## Parameters
| Parameter | Type | Description |
| --------- | ------- | ----------- |
| value | boolean | |
**Returns:**
this

View File

@ -0,0 +1,23 @@
---
sidebar_label: Locator.setTimeout
---
# Locator.setTimeout() method
#### Signature:
```typescript
class Locator {
setTimeout(timeout: number): this;
}
```
## Parameters
| Parameter | Type | Description |
| --------- | ------ | ----------- |
| timeout | number | |
**Returns:**
this

View File

@ -0,0 +1,23 @@
---
sidebar_label: Locator.setVisibility
---
# Locator.setVisibility() method
#### Signature:
```typescript
class Locator {
setVisibility(visibility: VisibilityOption): this;
}
```
## Parameters
| Parameter | Type | Description |
| ---------- | --------------------------------------------------- | ----------- |
| visibility | [VisibilityOption](./puppeteer.visibilityoption.md) | |
**Returns:**
this

View File

@ -0,0 +1,23 @@
---
sidebar_label: Locator.setWaitForEnabled
---
# Locator.setWaitForEnabled() method
#### Signature:
```typescript
class Locator {
setWaitForEnabled(value: boolean): this;
}
```
## Parameters
| Parameter | Type | Description |
| --------- | ------- | ----------- |
| value | boolean | |
**Returns:**
this

View File

@ -0,0 +1,23 @@
---
sidebar_label: Locator.setWaitForStableBoundingBox
---
# Locator.setWaitForStableBoundingBox() method
#### Signature:
```typescript
class Locator {
setWaitForStableBoundingBox(value: boolean): this;
}
```
## Parameters
| Parameter | Type | Description |
| --------- | ------- | ----------- |
| value | boolean | |
**Returns:**
this

View File

@ -0,0 +1,19 @@
---
sidebar_label: LocatorEmittedEvents
---
# LocatorEmittedEvents enum
All the events that a locator instance may emit.
#### Signature:
```typescript
export declare enum LocatorEmittedEvents
```
## Enumeration Members
| Member | Value | Description |
| ------ | ------------------------------- | ----------------------------------------------------------------------------------- |
| Action | <code>&quot;action&quot;</code> | Emitted every time before the locator performs an action on the located element(s). |

View File

@ -0,0 +1,17 @@
---
sidebar_label: LocatorEventObject
---
# LocatorEventObject interface
#### Signature:
```typescript
export interface LocatorEventObject
```
## Properties
| Property | Modifiers | Type | Description | Default |
| -------- | --------- | ----- | ----------- | ------- |
| action | | never | | |

View File

@ -0,0 +1,21 @@
---
sidebar_label: LocatorOptions
---
# LocatorOptions interface
#### Signature:
```typescript
export interface LocatorOptions
```
## Properties
| Property | Modifiers | Type | Description | Default |
| ---------------------------- | --------- | --------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------- |
| ensureElementIsInTheViewport | | boolean | Whether to scroll the element into viewport if not in the viewprot already. | <code>true</code> |
| timeout | | number | <p>Total timeout for the entire locator operation.</p><p>Pass <code>0</code> to disable timeout.</p> | <code>Page.getDefaultTimeout()</code> |
| visibility | | [VisibilityOption](./puppeteer.visibilityoption.md) | Whether to wait for the element to be <code>visible</code> or <code>hidden</code>. <code>null</code> to disable visibility checks. | |
| waitForEnabled | | boolean | Whether to wait for input elements to become enabled before the action. Applicable to <code>click</code> and <code>fill</code> actions. | <code>true</code> |
| waitForStableBoundingBox | | boolean | Whether to wait for the element's bounding box to be same between two animation frames. | <code>true</code> |

View File

@ -0,0 +1,29 @@
---
sidebar_label: Page.locator
---
# Page.locator() method
Creates a locator for the provided `selector`. See [Locator](./puppeteer.locator.md) for details and supported actions.
#### Signature:
```typescript
class Page {
locator(selector: string): Locator;
}
```
## Parameters
| Parameter | Type | Description |
| --------- | ------ | ----------- |
| selector | string | |
**Returns:**
[Locator](./puppeteer.locator.md)
## Remarks
Locators API is experimental and we will not follow semver for breaking change in the Locators API.

View File

@ -118,6 +118,7 @@ page.off('request', logRequest);
| [isDragInterceptionEnabled()](./puppeteer.page.isdraginterceptionenabled.md) | | <code>true</code> if drag events are being intercepted, <code>false</code> otherwise. |
| [isJavaScriptEnabled()](./puppeteer.page.isjavascriptenabled.md) | | <code>true</code> if the page has JavaScript enabled, <code>false</code> otherwise. |
| [isServiceWorkerBypassed()](./puppeteer.page.isserviceworkerbypassed.md) | | <code>true</code> if the service worker are being bypassed, <code>false</code> otherwise. |
| [locator(selector)](./puppeteer.page.locator.md) | | Creates a locator for the provided <code>selector</code>. See [Locator](./puppeteer.locator.md) for details and supported actions. |
| [mainFrame()](./puppeteer.page.mainframe.md) | | The page's main frame. |
| [metrics()](./puppeteer.page.metrics.md) | | Object containing metrics as key/value pairs. |
| [off(eventName, handler)](./puppeteer.page.off.md) | | |

View File

@ -0,0 +1,11 @@
---
sidebar_label: VisibilityOption
---
# VisibilityOption type
#### Signature:
```typescript
export type VisibilityOption = 'hidden' | 'visible' | null;
```

108
docs/guides/locators.md Normal file
View File

@ -0,0 +1,108 @@
# Locators
Locators is a new experimental API that combines `waitForSelector` and element
actions in a single unit. In combination with additional precondition checks
this allows locators to retry failed actions automatically leading to less flaky
automation scripts.
:::note
Locators API is experimental and we will not follow semver for breaking changes
in the Locators API.
:::
## Clicking an element
```ts
await page.locator('button').click();
```
The following preconditions are automatically checked:
- Ensures the element is in the viewport.
- Waits for the element to become
[visible](https://pptr.dev/api/puppeteer.elementhandle.isvisible/) or hidden.
- Waits for the element to become enabled.
- Waits for the element to have a stable bounding box over two consecutive
animation frames.
## Filling out an input
```ts
await page.locator('input').fill('value');
```
Automatically detects the input type and choose an approritate way to fill it out with the provided value.
The following preconditions are automatically checked:
- Ensures the element is in the viewport.
- Waits for the element to become
[visible](https://pptr.dev/api/puppeteer.elementhandle.isvisible/) or hidden.
- Waits for the element to become enabled.
- Waits for the element to have a stable bounding box over two consecutive
animation frames.
## Hover over an element
```ts
await page.locator('div').hover();
```
The following preconditions are automatically checked:
- Ensures the element is in the viewport.
- Waits for the element to become
[visible](https://pptr.dev/api/puppeteer.elementhandle.isvisible/) or hidden.
- Waits for the element to have a stable bounding box over two consecutive
animation frames.
## Scroll an element
```ts
await page.locator('div').scroll({
scrollLeft: 10,
scrollTop: 20,
});
```
The following preconditions are automatically checked:
- Ensures the element is in the viewport.
- Waits for the element to become
[visible](https://pptr.dev/api/puppeteer.elementhandle.isvisible/) or hidden.
- Waits for the element to have a stable bounding box over two consecutive
animation frames.
## Configuring locators
Locators can be configured to tune configure the preconditions and other other options:
```ts
await page
.locator('button')
.setEnsureElementIsInTheViewport(false)
.setTimeout(0)
.setVisibility(null)
.setWaitForEnabled(false)
.setWaitForStableBoundingBox(false)
.click();
```
## Getting locator events
Currently, locators support a single event that notifies you when the locator is about to perform the action:
```ts
let willClick = false;
await page
.locator('button')
.on(LocatorEmittedEvents.Action, () => {
willClick = true;
})
.click();
```
This event can be used for logging/debugging or other purposes. The event might
fire multiple times if the locator retries the action.

View File

@ -32,6 +32,8 @@ import {
NodeFor,
} from '../common/types.js';
import {Locator} from './Locator.js';
/**
* @public
*/
@ -345,6 +347,18 @@ export class Frame {
throw new Error('Not implemented');
}
/**
* Creates a locator for the provided `selector`. See {@link Locator} for
* details and supported actions.
*
* @remarks
* Locators API is experimental and we will not follow semver for breaking
* change in the Locators API.
*/
locator(selector: string): Locator {
return new Locator(this, selector);
}
/**
* Queries the frame for an element matching the given selector.
*

View File

@ -20,15 +20,16 @@ import {debugError} from '../common/util.js';
import {isErrorLike} from '../util/ErrorLike.js';
import {ElementHandle, BoundingBox, ClickOptions} from './ElementHandle.js';
import type {Frame} from './Frame.js';
import type {Page} from './Page.js';
/**
* @internal
* @public
*/
export type VisibilityOption = 'hidden' | 'visible' | null;
/**
* @internal
* @public
*/
export interface LocatorOptions {
/**
@ -73,7 +74,7 @@ const CONDITION_TIMEOUT = 1_000;
const WAIT_FOR_FUNCTION_DELAY = 100;
/**
* @internal
* @public
*/
export type ActionCondition = (
element: ElementHandle,
@ -81,7 +82,7 @@ export type ActionCondition = (
) => Promise<void>;
/**
* @internal
* @public
*/
export interface ActionOptions {
signal?: AbortSignal;
@ -91,7 +92,7 @@ export interface ActionOptions {
/**
* All the events that a locator instance may emit.
*
* @internal
* @public
*/
export enum LocatorEmittedEvents {
/**
@ -101,7 +102,7 @@ export enum LocatorEmittedEvents {
}
/**
* @internal
* @public
*/
export interface LocatorEventObject {
[LocatorEmittedEvents.Action]: never;
@ -109,29 +110,33 @@ export interface LocatorEventObject {
/**
* Locators describe a strategy of locating elements and performing an action on
* them. If the action fails because the element are not ready for the action,
* the whole operation is retried.
* them. If the action fails because the element is not ready for the action,
* the whole operation is retried. Various preconditions for a successful action
* are checked automatically.
*
* @internal
* @public
*/
export class Locator extends EventEmitter {
#page: Page;
#pageOrFrame: Page | Frame;
#selector: string;
#options: LocatorOptions;
constructor(
page: Page,
pageOrFrame: Page | Frame,
selector: string,
options: LocatorOptions = {
visibility: 'visible',
timeout: page.getDefaultTimeout(),
timeout:
'getDefaultTimeout' in pageOrFrame
? pageOrFrame.getDefaultTimeout()
: pageOrFrame.page().getDefaultTimeout(),
ensureElementIsInTheViewport: true,
waitForEnabled: true,
waitForStableBoundingBox: true,
}
) {
super();
this.#page = page;
this.#pageOrFrame = pageOrFrame;
this.#selector = selector;
this.#options = options;
}
@ -305,7 +310,7 @@ export class Locator extends EventEmitter {
if (!this.#options.waitForEnabled) {
return;
}
await this.#page.waitForFunction(
await this.#pageOrFrame.waitForFunction(
el => {
if (['button', 'textarea', 'input', 'select'].includes(el.tagName)) {
return !(el as HTMLInputElement).disabled;
@ -375,11 +380,14 @@ export class Locator extends EventEmitter {
await this.#waitForFunction(
async signal => {
// 1. Select the element without visibility checks.
const element = await this.#page.waitForSelector(this.#selector, {
visible: false,
timeout: this.#options.timeout,
signal,
});
const element = await this.#pageOrFrame.waitForSelector(
this.#selector,
{
visible: false,
timeout: this.#options.timeout,
signal,
}
);
// Retry if no element is found.
if (!element) {
return false;

View File

@ -819,7 +819,12 @@ export class Page extends EventEmitter {
}
/**
* @internal
* Creates a locator for the provided `selector`. See {@link Locator} for
* details and supported actions.
*
* @remarks
* Locators API is experimental and we will not follow semver for breaking
* change in the Locators API.
*/
locator(selector: string): Locator {
return new Locator(this, selector);

View File

@ -29,6 +29,29 @@ describe('Locator', function () {
setupTestBrowserHooks();
setupTestPageAndContextHooks();
it('should work with a frame', async () => {
const {page} = getTestState();
await page.setViewport({width: 500, height: 500});
await page.setContent(`
<button onclick="this.innerText = 'clicked';">test</button>
`);
let willClick = false;
await page
.mainFrame()
.locator('button')
.on(LocatorEmittedEvents.Action, () => {
willClick = true;
})
.click();
const button = await page.$('button');
const text = await button?.evaluate(el => {
return el.innerText;
});
expect(text).toBe('clicked');
expect(willClick).toBe(true);
});
it('should work without preconditions', async () => {
const {page} = getTestState();