Skip to main content

延展性

自訂選擇器引擎

Playwright 支援自訂選擇器引擎,透過 selectors.register() 註冊。

選擇器引擎應具備以下屬性:

  • query 函式用於查詢相對於 root 第一個符合 selector 的元素。
  • queryAll 函式用於查詢相對於 root 所有符合 selector 的元素。

預設情況下,引擎直接在框架的 JavaScript 情境中執行,例如可以呼叫應用程式定義的函式。若要將引擎與框架中的任何 JavaScript 隔離,但保留對 DOM 的存取,請使用 {contentScript: true} 選項註冊引擎。內容腳本引擎更安全,因為它受到保護,不會被全域物件的任何竄改影響,例如更改 Node.prototype 方法。所有內建選擇器引擎都以內容腳本執行。請注意,當引擎與其他自訂引擎一起使用時,不保證會以內容腳本執行。

選擇器必須在建立頁面前註冊。

以下範例註冊一個基於標籤名稱查詢元素的選擇器引擎:

baseTest.ts
import { test as base } from '@playwright/test';

export { expect } from '@playwright/test';

// Must be a function that evaluates to a selector engine instance.
const createTagNameEngine = () => ({
// Returns the first element matching given selector in the root's subtree.
query(root, selector) {
return root.querySelector(selector);
},

// Returns all elements matching given selector in the root's subtree.
queryAll(root, selector) {
return Array.from(root.querySelectorAll(selector));
}
});

export const test = base.extend<{}, { selectorRegistration: void }>({
// Register selectors once per worker.
selectorRegistration: [async ({ playwright }, use) => {
// Register the engine. Selectors will be prefixed with "tag=".
await playwright.selectors.register('tag', createTagNameEngine);
await use();
}, { scope: 'worker', auto: true }],
});
example.spec.ts
import { test, expect } from './baseTest';

test('selector engine test', async ({ page }) => {
// Now we can use 'tag=' selectors.
const button = page.locator('tag=button');
await button.click();

// We can combine it with built-in locators.
await page.locator('tag=div').getByText('Click me').click();

// We can use it in any methods supporting selectors.
await expect(page.locator('tag=button')).toHaveCount(3);
});