Handles
Playwright can create handles to the page DOM elements or any other objects inside the page. These handles live in the Playwright process, whereas the actual objects live in the browser. There are two types of handles:
- JSHandle to reference any JavaScript objects in the page
- ElementHandle to reference DOM elements in the page, it has extra methods that allow performing actions on the elements and asserting their properties.
Since any DOM element in the page is also a JavaScript object, any ElementHandle is a JSHandle as well.
Handles are used to perform operations on those actual objects in the page. You can evaluate on a handle, get handle properties, pass handle as an evaluation parameter, serialize page object into JSON etc. See the JSHandle class API for these and methods.
#
API referenceHere is the easiest way to obtain a JSHandle.
#
Element Handlesnote
It is recommended to use selector-based actions like page.click(selector[, options]) rather than using the ElementHandle for input actions, unless your use case specifically requires the use of handles.
When ElementHandle is required, it is recommended to fetch it with the page.waitForSelector(selector[, options]) or frame.waitForSelector(selector[, options]) methods. These APIs wait for the element to be attached and visible.
#
Handles as parametersHandles can be passed into the page.evaluate(pageFunction[, arg]) and similar methods. The following snippet creates a new array in the page, initializes it with data and returns a handle to this array into Playwright. It then uses the handle in subsequent evaluations:
#
Handle LifecycleHandles can be acquired using the page methods such as page.evaluateHandle(pageFunction[, arg]), page.$(selector) or page.$$(selector) or their frame counterparts frame.evaluateHandle(pageFunction[, arg]), frame.$(selector) or frame.$$(selector). Once created, handles will retain object from garbage collection unless page navigates or the handle is manually disposed via the jsHandle.dispose() method.