Chrome 擴充功能
簡介
note
擴充功能僅在使用持久性上下文啟動的 Chrome / Chromium 中工作。使用自訂瀏覽器參數需自行承擔風險,因為其中一些可能會破壞 Playwright 功能。
以下是取得 background page 的程式碼,這個 Manifest v2 擴充套件的來源位於 ./my-extension
:
const { chromium } = require('playwright');
(async () => {
const pathToExtension = require('path').join(__dirname, 'my-extension');
const userDataDir = '/tmp/test-user-data-dir';
const browserContext = await chromium.launchPersistentContext(userDataDir, {
headless: false,
args: [
`--disable-extensions-except=${pathToExtension}`,
`--load-extension=${pathToExtension}`
]
});
let [backgroundPage] = browserContext.backgroundPages();
if (!backgroundPage)
backgroundPage = await browserContext.waitForEvent('backgroundpage');
// Test the background page as you would any other page.
await browserContext.close();
})();
測試
為了在執行測試時載入擴充功能,您可以使用測試裝置來設定上下文。您也可以動態檢索擴充功能 ID,並使用它來載入和測試彈出頁面範例。
首先,新增將載入擴充功能的固定裝置:
fixtures.ts
import { test as base, chromium, type BrowserContext } from '@playwright/test';
import path from 'path';
export const test = base.extend<{
context: BrowserContext;
extensionId: string;
}>({
context: async ({ }, use) => {
const pathToExtension = path.join(__dirname, 'my-extension');
const context = await chromium.launchPersistentContext('', {
headless: false,
args: [
`--disable-extensions-except=${pathToExtension}`,
`--load-extension=${pathToExtension}`,
],
});
await use(context);
await context.close();
},
extensionId: async ({ context }, use) => {
/*
// for manifest v2:
let [background] = context.backgroundPages()
if (!background)
background = await context.waitForEvent('backgroundpage')
*/
// for manifest v3:
let [background] = context.serviceWorkers();
if (!background)
background = await context.waitForEvent('serviceworker');
const extensionId = background.url().split('/')[2];
await use(extensionId);
},
});
export const expect = test.expect;
然後在測試中使用這些裝置:
import { test, expect } from './fixtures';
test('example test', async ({ page }) => {
await page.goto('https://example.com');
await expect(page.locator('body')).toHaveText('Changed by my-extension');
});
test('popup page', async ({ page, extensionId }) => {
await page.goto(`chrome-extension://${extensionId}/popup.html`);
await expect(page.locator('body')).toHaveText('my-extension popup');
});
無頭模式
danger
headless=new
模式不受 Playwright 官方支持,可能會導致意外行為。
預設情況下,Chrome 在 Playwright 中的無頭模式不支援 Chrome 擴充功能。為了克服這一限制,你可以使用以下程式碼在新的無頭模式下執行 Chrome 的持久性上下文:
fixtures.ts
// ...
const pathToExtension = path.join(__dirname, 'my-extension');
const context = await chromium.launchPersistentContext('', {
headless: false,
args: [
`--headless=new`,
`--disable-extensions-except=${pathToExtension}`,
`--load-extension=${pathToExtension}`,
],
});
// ...