有没有办法使用Puppeteer测试Chrome扩展程序?例如,扩展程序可以检测Chrome是否已在" test"模式提供不同的UI,检查内容脚本是否正常工作等?
答案 0 :(得分:14)
在--user-agent
中传递puppeteer.launch()
是一种使用自定义值覆盖浏览器UA的有用方法。然后,您的扩展程序可以在其后台页面中回读navigator.userAgent
,并确定Chrome是与Puppeteer一起发布的。此时,您可以提供不同的代码路径来测试crx与正常操作。
<强> puppeteer_script.js
const puppeteer = require('puppeteer');
const CRX_PATH = '/path/to/crx/folder/';
puppeteer.launch({
headless: false, // extensions only supported in full chrome.
args: [
`--disable-extensions-except=${CRX_PATH}`,
`--load-extension=${CRX_PATH}`,
'--user-agent=PuppeteerAgent'
]
}).then(async browser => {
// ... do some testing ...
await browser.close();
});
扩展程序 background.js
chrome.runtime.onInstalled.addListener(details => {
console.log(navigator.userAgent); // "PuppeteerAgent"
});
或者,如果您想保留浏览器的原始UA字符串,则会变得棘手。
<强> background.js
let LAUNCHED_BY_PUPPETEER = false; // reuse in other parts of your crx as needed.
chrome.tabs.onUpdated.addListener((tabId, info, tab) => {
if (!LAUNCHED_BY_PUPPETEER && tab.title.includes('PuppeteerAgent')) {
chrome.tabs.remove(tabId);
LAUNCHED_BY_PUPPETEER = true;
}
});
<强> puppeteer_script.js
const puppeteer = require('puppeteer');
const CRX_PATH = '/path/to/crx/folder/';
puppeteer.launch({
headless: false, // extensions only supported in full chrome.
args: [
`--disable-extensions-except=${CRX_PATH}`,
`--load-extension=${CRX_PATH}`,
]
}).then(async browser => {
const page = await browser.newPage();
await page.evaluate("document.title = 'PuppeteerAgent'");
// ... do some testing ...
await browser.close();
});
注意:缺点是这种方法需要&#34;标签&#34; manifest.json中的权限。
让我们说你想测试你的弹出页面用户界面?一种方法是直接导航到其chrome-extension://
URL,然后使用puppeteer进行UI测试:
// Can we navigate to a chrome-extension page? YES!
const page = await browser.newPage();
await page.goto('chrome-extension://ipfiboohojhbonenbbppflmpfkakjhed/popup.html');
// click buttons, test UI elements, etc.
要为测试创建稳定的扩展ID,请查看:https://stackoverflow.com/a/23877974/274673