From 1f978f5fc5f0580859ad423e952595979f50d5a9 Mon Sep 17 00:00:00 2001 From: Alex Rudenko Date: Fri, 2 Jun 2023 19:46:10 +0200 Subject: [PATCH] feat: implement Locators (#10305) --- docs/api/index.md | 7 ++ docs/api/puppeteer.actioncondition.md | 16 +++ docs/api/puppeteer.actionoptions.md | 18 +++ docs/api/puppeteer.frame.locator.md | 29 +++++ docs/api/puppeteer.frame.md | 1 + docs/api/puppeteer.locator._constructor_.md | 27 +++++ docs/api/puppeteer.locator.click.md | 27 +++++ docs/api/puppeteer.locator.fill.md | 31 +++++ docs/api/puppeteer.locator.hover.md | 23 ++++ docs/api/puppeteer.locator.md | 38 ++++++ docs/api/puppeteer.locator.off.md | 27 +++++ docs/api/puppeteer.locator.on.md | 27 +++++ docs/api/puppeteer.locator.once.md | 27 +++++ docs/api/puppeteer.locator.scroll.md | 27 +++++ ...locator.setensureelementisintheviewport.md | 23 ++++ docs/api/puppeteer.locator.settimeout.md | 23 ++++ docs/api/puppeteer.locator.setvisibility.md | 23 ++++ .../puppeteer.locator.setwaitforenabled.md | 23 ++++ ...eer.locator.setwaitforstableboundingbox.md | 23 ++++ docs/api/puppeteer.locatoremittedevents.md | 19 +++ docs/api/puppeteer.locatoreventobject.md | 17 +++ docs/api/puppeteer.locatoroptions.md | 21 ++++ docs/api/puppeteer.page.locator.md | 29 +++++ docs/api/puppeteer.page.md | 1 + docs/api/puppeteer.visibilityoption.md | 11 ++ docs/guides/locators.md | 108 ++++++++++++++++++ packages/puppeteer-core/src/api/Frame.ts | 14 +++ packages/puppeteer-core/src/api/Locator.ts | 46 +++++--- packages/puppeteer-core/src/api/Page.ts | 7 +- test/src/locator.spec.ts | 23 ++++ 30 files changed, 716 insertions(+), 20 deletions(-) create mode 100644 docs/api/puppeteer.actioncondition.md create mode 100644 docs/api/puppeteer.actionoptions.md create mode 100644 docs/api/puppeteer.frame.locator.md create mode 100644 docs/api/puppeteer.locator._constructor_.md create mode 100644 docs/api/puppeteer.locator.click.md create mode 100644 docs/api/puppeteer.locator.fill.md create mode 100644 docs/api/puppeteer.locator.hover.md create mode 100644 docs/api/puppeteer.locator.md create mode 100644 docs/api/puppeteer.locator.off.md create mode 100644 docs/api/puppeteer.locator.on.md create mode 100644 docs/api/puppeteer.locator.once.md create mode 100644 docs/api/puppeteer.locator.scroll.md create mode 100644 docs/api/puppeteer.locator.setensureelementisintheviewport.md create mode 100644 docs/api/puppeteer.locator.settimeout.md create mode 100644 docs/api/puppeteer.locator.setvisibility.md create mode 100644 docs/api/puppeteer.locator.setwaitforenabled.md create mode 100644 docs/api/puppeteer.locator.setwaitforstableboundingbox.md create mode 100644 docs/api/puppeteer.locatoremittedevents.md create mode 100644 docs/api/puppeteer.locatoreventobject.md create mode 100644 docs/api/puppeteer.locatoroptions.md create mode 100644 docs/api/puppeteer.page.locator.md create mode 100644 docs/api/puppeteer.visibilityoption.md create mode 100644 docs/guides/locators.md diff --git a/docs/api/index.md b/docs/api/index.md index eea71759880..26ee298149e 100644 --- a/docs/api/index.md +++ b/docs/api/index.md @@ -29,6 +29,7 @@ sidebar_label: API | [JSCoverage](./puppeteer.jscoverage.md) | | | [JSHandle](./puppeteer.jshandle.md) |

Represents a reference to a JavaScript object. Instances can be created using [Page.evaluateHandle()](./puppeteer.page.evaluatehandle.md).

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.

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.

| | [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) |

Page provides methods to interact with a single tab or [extension background page](https://developer.chrome.com/extensions/background_pages) in the browser.

:::note

One Browser instance might have multiple Page instances.

:::

| | [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 puppeteer.launch 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) | | diff --git a/docs/api/puppeteer.actioncondition.md b/docs/api/puppeteer.actioncondition.md new file mode 100644 index 00000000000..64e3f7a1687 --- /dev/null +++ b/docs/api/puppeteer.actioncondition.md @@ -0,0 +1,16 @@ +--- +sidebar_label: ActionCondition +--- + +# ActionCondition type + +#### Signature: + +```typescript +export type ActionCondition = ( + element: ElementHandle, + signal: AbortSignal +) => Promise; +``` + +**References:** [ElementHandle](./puppeteer.elementhandle.md) diff --git a/docs/api/puppeteer.actionoptions.md b/docs/api/puppeteer.actionoptions.md new file mode 100644 index 00000000000..e5cd3722bf0 --- /dev/null +++ b/docs/api/puppeteer.actionoptions.md @@ -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 | optional | AbortSignal | | | diff --git a/docs/api/puppeteer.frame.locator.md b/docs/api/puppeteer.frame.locator.md new file mode 100644 index 00000000000..7ac09ec1af0 --- /dev/null +++ b/docs/api/puppeteer.frame.locator.md @@ -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. diff --git a/docs/api/puppeteer.frame.md b/docs/api/puppeteer.frame.md index 0450f2c8a01..574284b34ad 100644 --- a/docs/api/puppeteer.frame.md +++ b/docs/api/puppeteer.frame.md @@ -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 selector. | | [isDetached()](./puppeteer.frame.isdetached.md) | | Istrue if the frame has been detached. Otherwise, false. | | [isOOPFrame()](./puppeteer.frame.isoopframe.md) | | Is true if the frame is an out-of-process (OOP) frame. Otherwise, false. | +| [locator(selector)](./puppeteer.frame.locator.md) | | Creates a locator for the provided selector. See [Locator](./puppeteer.locator.md) for details and supported actions. | | [name()](./puppeteer.frame.name.md) | | The frame's name 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 null. | diff --git a/docs/api/puppeteer.locator._constructor_.md b/docs/api/puppeteer.locator._constructor_.md new file mode 100644 index 00000000000..59fec1903b9 --- /dev/null +++ b/docs/api/puppeteer.locator._constructor_.md @@ -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)_ | diff --git a/docs/api/puppeteer.locator.click.md b/docs/api/puppeteer.locator.click.md new file mode 100644 index 00000000000..77f99e272bc --- /dev/null +++ b/docs/api/puppeteer.locator.click.md @@ -0,0 +1,27 @@ +--- +sidebar_label: Locator.click +--- + +# Locator.click() method + +#### Signature: + +```typescript +class Locator { + click( + clickOptions?: ClickOptions & { + signal?: AbortSignal; + } + ): Promise; +} +``` + +## Parameters + +| Parameter | Type | Description | +| ------------ | --------------------------------------------------------------------------- | ------------ | +| clickOptions | [ClickOptions](./puppeteer.clickoptions.md) & { signal?: AbortSignal; } | _(Optional)_ | + +**Returns:** + +Promise<void> diff --git a/docs/api/puppeteer.locator.fill.md b/docs/api/puppeteer.locator.fill.md new file mode 100644 index 00000000000..dce869aa1e8 --- /dev/null +++ b/docs/api/puppeteer.locator.fill.md @@ -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; +} +``` + +## Parameters + +| Parameter | Type | Description | +| ----------- | ------------------------- | ------------ | +| value | string | | +| fillOptions | { signal?: AbortSignal; } | _(Optional)_ | + +**Returns:** + +Promise<void> diff --git a/docs/api/puppeteer.locator.hover.md b/docs/api/puppeteer.locator.hover.md new file mode 100644 index 00000000000..d9a298e850e --- /dev/null +++ b/docs/api/puppeteer.locator.hover.md @@ -0,0 +1,23 @@ +--- +sidebar_label: Locator.hover +--- + +# Locator.hover() method + +#### Signature: + +```typescript +class Locator { + hover(hoverOptions?: {signal?: AbortSignal}): Promise; +} +``` + +## Parameters + +| Parameter | Type | Description | +| ------------ | ------------------------- | ------------ | +| hoverOptions | { signal?: AbortSignal; } | _(Optional)_ | + +**Returns:** + +Promise<void> diff --git a/docs/api/puppeteer.locator.md b/docs/api/puppeteer.locator.md new file mode 100644 index 00000000000..5fa22e27c7e --- /dev/null +++ b/docs/api/puppeteer.locator.md @@ -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 Locator 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) | | | diff --git a/docs/api/puppeteer.locator.off.md b/docs/api/puppeteer.locator.off.md new file mode 100644 index 00000000000..94d8ff142e6 --- /dev/null +++ b/docs/api/puppeteer.locator.off.md @@ -0,0 +1,27 @@ +--- +sidebar_label: Locator.off +--- + +# Locator.off() method + +#### Signature: + +```typescript +class Locator { + off( + eventName: K, + handler: (event: LocatorEventObject[K]) => void + ): this; +} +``` + +## Parameters + +| Parameter | Type | Description | +| --------- | -------------------------------------------------------------------------------- | ----------- | +| eventName | K | | +| handler | (event: [LocatorEventObject](./puppeteer.locatoreventobject.md)\[K\]) => void | | + +**Returns:** + +this diff --git a/docs/api/puppeteer.locator.on.md b/docs/api/puppeteer.locator.on.md new file mode 100644 index 00000000000..487e21412cb --- /dev/null +++ b/docs/api/puppeteer.locator.on.md @@ -0,0 +1,27 @@ +--- +sidebar_label: Locator.on +--- + +# Locator.on() method + +#### Signature: + +```typescript +class Locator { + on( + eventName: K, + handler: (event: LocatorEventObject[K]) => void + ): this; +} +``` + +## Parameters + +| Parameter | Type | Description | +| --------- | -------------------------------------------------------------------------------- | ----------- | +| eventName | K | | +| handler | (event: [LocatorEventObject](./puppeteer.locatoreventobject.md)\[K\]) => void | | + +**Returns:** + +this diff --git a/docs/api/puppeteer.locator.once.md b/docs/api/puppeteer.locator.once.md new file mode 100644 index 00000000000..54037d294c2 --- /dev/null +++ b/docs/api/puppeteer.locator.once.md @@ -0,0 +1,27 @@ +--- +sidebar_label: Locator.once +--- + +# Locator.once() method + +#### Signature: + +```typescript +class Locator { + once( + eventName: K, + handler: (event: LocatorEventObject[K]) => void + ): this; +} +``` + +## Parameters + +| Parameter | Type | Description | +| --------- | -------------------------------------------------------------------------------- | ----------- | +| eventName | K | | +| handler | (event: [LocatorEventObject](./puppeteer.locatoreventobject.md)\[K\]) => void | | + +**Returns:** + +this diff --git a/docs/api/puppeteer.locator.scroll.md b/docs/api/puppeteer.locator.scroll.md new file mode 100644 index 00000000000..1781c7543b2 --- /dev/null +++ b/docs/api/puppeteer.locator.scroll.md @@ -0,0 +1,27 @@ +--- +sidebar_label: Locator.scroll +--- + +# Locator.scroll() method + +#### Signature: + +```typescript +class Locator { + scroll(scrollOptions?: { + scrollTop?: number; + scrollLeft?: number; + signal?: AbortSignal; + }): Promise; +} +``` + +## Parameters + +| Parameter | Type | Description | +| ------------- | ------------------------------------------------------------------ | ------------ | +| scrollOptions | { scrollTop?: number; scrollLeft?: number; signal?: AbortSignal; } | _(Optional)_ | + +**Returns:** + +Promise<void> diff --git a/docs/api/puppeteer.locator.setensureelementisintheviewport.md b/docs/api/puppeteer.locator.setensureelementisintheviewport.md new file mode 100644 index 00000000000..e83c5d37e70 --- /dev/null +++ b/docs/api/puppeteer.locator.setensureelementisintheviewport.md @@ -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 diff --git a/docs/api/puppeteer.locator.settimeout.md b/docs/api/puppeteer.locator.settimeout.md new file mode 100644 index 00000000000..33099941c66 --- /dev/null +++ b/docs/api/puppeteer.locator.settimeout.md @@ -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 diff --git a/docs/api/puppeteer.locator.setvisibility.md b/docs/api/puppeteer.locator.setvisibility.md new file mode 100644 index 00000000000..7d9430df823 --- /dev/null +++ b/docs/api/puppeteer.locator.setvisibility.md @@ -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 diff --git a/docs/api/puppeteer.locator.setwaitforenabled.md b/docs/api/puppeteer.locator.setwaitforenabled.md new file mode 100644 index 00000000000..a076de776f6 --- /dev/null +++ b/docs/api/puppeteer.locator.setwaitforenabled.md @@ -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 diff --git a/docs/api/puppeteer.locator.setwaitforstableboundingbox.md b/docs/api/puppeteer.locator.setwaitforstableboundingbox.md new file mode 100644 index 00000000000..88c85fe7c1f --- /dev/null +++ b/docs/api/puppeteer.locator.setwaitforstableboundingbox.md @@ -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 diff --git a/docs/api/puppeteer.locatoremittedevents.md b/docs/api/puppeteer.locatoremittedevents.md new file mode 100644 index 00000000000..0d45cca2615 --- /dev/null +++ b/docs/api/puppeteer.locatoremittedevents.md @@ -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 | "action" | Emitted every time before the locator performs an action on the located element(s). | diff --git a/docs/api/puppeteer.locatoreventobject.md b/docs/api/puppeteer.locatoreventobject.md new file mode 100644 index 00000000000..8b70ec2a8b9 --- /dev/null +++ b/docs/api/puppeteer.locatoreventobject.md @@ -0,0 +1,17 @@ +--- +sidebar_label: LocatorEventObject +--- + +# LocatorEventObject interface + +#### Signature: + +```typescript +export interface LocatorEventObject +``` + +## Properties + +| Property | Modifiers | Type | Description | Default | +| -------- | --------- | ----- | ----------- | ------- | +| action | | never | | | diff --git a/docs/api/puppeteer.locatoroptions.md b/docs/api/puppeteer.locatoroptions.md new file mode 100644 index 00000000000..8af6157226f --- /dev/null +++ b/docs/api/puppeteer.locatoroptions.md @@ -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. | true | +| timeout | | number |

Total timeout for the entire locator operation.

Pass 0 to disable timeout.

| Page.getDefaultTimeout() | +| visibility | | [VisibilityOption](./puppeteer.visibilityoption.md) | Whether to wait for the element to be visible or hidden. null to disable visibility checks. | | +| waitForEnabled | | boolean | Whether to wait for input elements to become enabled before the action. Applicable to click and fill actions. | true | +| waitForStableBoundingBox | | boolean | Whether to wait for the element's bounding box to be same between two animation frames. | true | diff --git a/docs/api/puppeteer.page.locator.md b/docs/api/puppeteer.page.locator.md new file mode 100644 index 00000000000..8dcc9bb2856 --- /dev/null +++ b/docs/api/puppeteer.page.locator.md @@ -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. diff --git a/docs/api/puppeteer.page.md b/docs/api/puppeteer.page.md index 4b6b655aecd..27d0a2b6ebf 100644 --- a/docs/api/puppeteer.page.md +++ b/docs/api/puppeteer.page.md @@ -118,6 +118,7 @@ page.off('request', logRequest); | [isDragInterceptionEnabled()](./puppeteer.page.isdraginterceptionenabled.md) | | true if drag events are being intercepted, false otherwise. | | [isJavaScriptEnabled()](./puppeteer.page.isjavascriptenabled.md) | | true if the page has JavaScript enabled, false otherwise. | | [isServiceWorkerBypassed()](./puppeteer.page.isserviceworkerbypassed.md) | | true if the service worker are being bypassed, false otherwise. | +| [locator(selector)](./puppeteer.page.locator.md) | | Creates a locator for the provided selector. 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) | | | diff --git a/docs/api/puppeteer.visibilityoption.md b/docs/api/puppeteer.visibilityoption.md new file mode 100644 index 00000000000..1af2ec00500 --- /dev/null +++ b/docs/api/puppeteer.visibilityoption.md @@ -0,0 +1,11 @@ +--- +sidebar_label: VisibilityOption +--- + +# VisibilityOption type + +#### Signature: + +```typescript +export type VisibilityOption = 'hidden' | 'visible' | null; +``` diff --git a/docs/guides/locators.md b/docs/guides/locators.md new file mode 100644 index 00000000000..0985a28dd28 --- /dev/null +++ b/docs/guides/locators.md @@ -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. diff --git a/packages/puppeteer-core/src/api/Frame.ts b/packages/puppeteer-core/src/api/Frame.ts index 00dac50c079..2567d733239 100644 --- a/packages/puppeteer-core/src/api/Frame.ts +++ b/packages/puppeteer-core/src/api/Frame.ts @@ -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. * diff --git a/packages/puppeteer-core/src/api/Locator.ts b/packages/puppeteer-core/src/api/Locator.ts index cc0bb7e9d4b..97cfaefe820 100644 --- a/packages/puppeteer-core/src/api/Locator.ts +++ b/packages/puppeteer-core/src/api/Locator.ts @@ -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; /** - * @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; diff --git a/packages/puppeteer-core/src/api/Page.ts b/packages/puppeteer-core/src/api/Page.ts index 6a5854a825b..3abd2f732c0 100644 --- a/packages/puppeteer-core/src/api/Page.ts +++ b/packages/puppeteer-core/src/api/Page.ts @@ -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); diff --git a/test/src/locator.spec.ts b/test/src/locator.spec.ts index 7285a46b7b0..7e6154cc226 100644 --- a/test/src/locator.spec.ts +++ b/test/src/locator.spec.ts @@ -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(` + + `); + 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();