Học Playwright tiếng Việt, Cộng đồng Playwright cho người Việt

Vọc Vạch Playwright

[Vọc Playwright ] – Handles

https://playwright.dev/docs/handles

Giới thiệu

  • Playwight có thể tạo các handle tới các DOM element hoặc tới các thành phần của page.
  • Các handle này được xử lý bởi Playwight.
  • Có 2 loại handle:
    • JSHandle: liên kết tới một Javascript object trong page
    • ElemenentHandle: liên kết tới DOM elements trong page. Có các method bổ sung để thực hiện một số action trên phần tử và assert các thuộc tính của chúng.
  • Vì bất cứ DOM element nào trong page cũng là một Javascript object, nên bạn có thể dùng cả ElementHandle và JSHandle đều được.
  • Handle thường dùng để thực hiện các action ở các object page.
  • Bạn có thể evaluate handle, lấy property của handle, đưa handle vào trong một evaluator như thể một parameter,…

API reference

  • Để tạo 1 JSHandle thì cách đơn giản nhất là:
const jsHandle = await page.evaluateHandle('window');
//  Use jsHandle for evaluations.

Element handles

  • Lưu ý: Element handle không được khuyến khích dùng. Anh em đọc cho vui. Nên dùng locator.
  • Khi dùng ElementHandle, bạn nên dùng page.waitForSelector() hoặc frame.waitForSelector()
    • Các API này sẽ chờ tới khi element được attach vào DOM và visible.
// Get the element handle
const elementHandle = page.waitForSelector('#box');

// Assert bounding box for the element
const boundingBox = await elementHandle.boundingBox();
expect(boundingBox.width).toBe(100);

// Assert attribute for the element
const classNames = await elementHandle.getAttribute('class');
expect(classNames.includes('highlighted')).toBeTruthy();

Handles as parameters

  • Handle có thể được pass vào hàm page.evaluate().
  • Trong ví dụ dưới đây, tạo mới một array với giá trị là [1], sau đó trả về cho Playwright
// Create new array in page.
const myArrayHandle = await page.evaluateHandle(() => {
  window.myArray = [1];
  return myArray;
});

// Get the length of the array.
const length = await page.evaluate(a => a.length, myArrayHandle);

// Add one more element to the array using the handle
await page.evaluate(arg => arg.myArray.push(arg.newElement), {
  myArray: myArrayHandle,
  newElement: 2
});

// Release the object when it's no longer needed.
await myArrayHandle.dispose();

Trả lời