跳到主要内容
版本:23.11.1

Chrome 扩展

Puppeteer 可用于测试 Chrome 扩展。

注意

扩展在 chrome-headless-shell (headless: 'shell') 中不可用,也称为旧的无头模式。

以下代码用于获取位于 ./my-extension 中的扩展的后台页面的句柄

import puppeteer from 'puppeteer';
import path from 'path';

const pathToExtension = path.join(process.cwd(), 'my-extension');
const browser = await puppeteer.launch({
args: [
`--disable-extensions-except=${pathToExtension}`,
`--load-extension=${pathToExtension}`,
],
});
const backgroundPageTarget = await browser.waitForTarget(
target => target.type() === 'background_page',
);
const backgroundPage = await backgroundPageTarget.page();
// Test the background page as you would any other page.
await browser.close();
注意

Chrome Manifest V3 扩展具有类型为 'service_worker' 的后台 ServiceWorker,而不是类型为 'background_page' 的页面。

import puppeteer from 'puppeteer';
import path from 'path';

const pathToExtension = path.join(process.cwd(), 'my-extension');
const browser = await puppeteer.launch({
args: [
`--disable-extensions-except=${pathToExtension}`,
`--load-extension=${pathToExtension}`,
],
});

const workerTarget = await browser.waitForTarget(
// Assumes that there is only one service worker created by the extension and its URL ends with background.js.
target =>
target.type() === 'service_worker' &&
target.url().endsWith('background.js'),
);

const worker = await workerTarget.worker();

// Open a popup (available for Canary channels).
await worker.evaluate('chrome.action.openPopup();');

const popupTarget = await browser.waitForTarget(
// Assumes that there is only one page with the URL ending with popup.html and that is the popup created by the extension.
target => target.type() === 'page' && target.url().endsWith('popup.html'),
);

const popupPage = popupTarget.asPage();

// Test the popup page as you would any other page.

await browser.close();
注意

目前无法测试扩展内容脚本。