跳至主要内容

Chrome扩展

简介

note

扩展程序仅在通过持久化上下文启动的Chrome/Chromium浏览器中生效。使用自定义浏览器参数存在风险,某些参数可能会破坏Playwright的功能。

以下代码片段检索了位于./my-extension目录下的Manifest v2扩展程序的background page

注意使用chromium通道可以在无头模式下运行扩展程序。或者,您也可以在有头模式下启动浏览器。

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, {
channel: 'chromium',
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,并利用它来加载和测试弹出页面等。

注意使用chromium通道可以在无头模式下运行扩展程序。或者,您也可以在有头模式下启动浏览器。

首先,添加将加载扩展的fixtures:

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('', {
channel: 'chromium',
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;

然后在测试中使用这些fixtures:

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');
});