106 lines
2.5 KiB
JavaScript
106 lines
2.5 KiB
JavaScript
/**
|
|
* 浏览器配置
|
|
* 支持 Puppeteer 和 Playwright
|
|
*/
|
|
|
|
const fs = require('fs');
|
|
|
|
// 浏览器可执行路径配置
|
|
const browserPaths = {
|
|
// Linux
|
|
linux: {
|
|
chromium: '/usr/bin/chromium-browser', // 优先使用系统 chromium
|
|
chromiumAlt: '/usr/bin/chromium',
|
|
chrome: '/usr/bin/google-chrome',
|
|
snapChromium: '/snap/bin/chromium',
|
|
},
|
|
// macOS
|
|
darwin: {
|
|
chrome: '/Applications/Google Chrome.app/Contents/MacOS/Google Chrome',
|
|
chromium: '/Applications/Chromium.app/Contents/MacOS/Chromium',
|
|
},
|
|
// Windows
|
|
win32: {
|
|
chrome: 'C:\\Program Files\\Google\\Chrome\\Application\\chrome.exe',
|
|
chromium: 'C:\\Program Files\\Chromium\\Application\\chromium.exe',
|
|
}
|
|
};
|
|
|
|
// 获取当前平台的浏览器路径
|
|
function getBrowserPath() {
|
|
const platform = process.platform;
|
|
const paths = browserPaths[platform] || browserPaths.linux;
|
|
|
|
// 按优先级返回所有可能的路径
|
|
return [
|
|
process.env.PUPPETEER_EXECUTABLE_PATH,
|
|
process.env.CHROME_BIN,
|
|
paths.chromium,
|
|
paths.chromiumAlt,
|
|
paths.chrome,
|
|
'/usr/bin/chromium',
|
|
].filter(Boolean);
|
|
}
|
|
|
|
// 查找第一个可用的浏览器
|
|
function findAvailableBrowser() {
|
|
const paths = getBrowserPath();
|
|
for (const p of paths) {
|
|
if (fs.existsSync(p)) {
|
|
return p;
|
|
}
|
|
}
|
|
return null;
|
|
}
|
|
|
|
// 浏览器启动配置 (Puppeteer)
|
|
function getLaunchOptions() {
|
|
const executablePath = findAvailableBrowser();
|
|
|
|
if (!executablePath) {
|
|
throw new Error('未找到可用的浏览器,请安装 Chromium 或 Chrome');
|
|
}
|
|
|
|
return {
|
|
headless: 'new', // 新的 headless 模式
|
|
args: [
|
|
'--no-sandbox',
|
|
'--disable-setuid-sandbox',
|
|
'--disable-dev-shm-usage',
|
|
'--disable-accelerated-2d-canvas',
|
|
'--disable-gpu',
|
|
'--window-size=1920,1080',
|
|
'--disable-blink-features=AutomationControlled', // 隐藏自动化特征
|
|
],
|
|
ignoreDefaultArgs: ['--enable-automation'], // 移除自动化标志
|
|
executablePath,
|
|
timeout: 30000,
|
|
};
|
|
}
|
|
|
|
// Playwright 配置
|
|
function getPlaywrightOptions() {
|
|
const executablePath = findAvailableBrowser();
|
|
|
|
if (!executablePath) {
|
|
throw new Error('未找到可用的浏览器,请安装 Chromium 或 Chrome');
|
|
}
|
|
|
|
return {
|
|
headless: true,
|
|
args: [
|
|
'--no-sandbox',
|
|
'--disable-setuid-sandbox',
|
|
'--disable-dev-shm-usage',
|
|
],
|
|
executablePath,
|
|
};
|
|
}
|
|
|
|
module.exports = {
|
|
getLaunchOptions,
|
|
getPlaywrightOptions,
|
|
getBrowserPath,
|
|
findAvailableBrowser,
|
|
};
|