Skip to main content
Version: 23.10.1

Chrome 扩展程序

¥Chrome Extensions

Puppeteer 可用于测试 Chrome 扩展。

¥Puppeteer can be used for testing Chrome Extensions.

提醒

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

¥Extensions are not available in chrome-headless-shell (headless: 'shell'), also known as the old headless mode.

以下是获取源位于 ./my-extension 的扩展的 背景页 句柄的代码:

¥The following is code for getting a handle to the background page of an extension whose source is located in ./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' 类型的页面。

¥Chrome Manifest V3 extensions have a background ServiceWorker of type 'service_worker', instead of a page of type '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();
注意

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

¥It is not yet possible to test extension content scripts.