diff --git a/src/services/browser-adapter.ts b/src/services/browser-adapter.ts index dc60a14..f79e21b 100644 --- a/src/services/browser-adapter.ts +++ b/src/services/browser-adapter.ts @@ -1,4 +1,5 @@ // @ts-nocheck +import fs from "node:fs"; import { chromium, firefox } from "playwright"; const visibleBrowsers = new Set(); @@ -48,8 +49,36 @@ export async function scrapePage(url, options = {}) { } function launchBrowser(engine, headless) { - const browserType = String(engine).toLowerCase() === "firefox" ? firefox : chromium; - return browserType.launch({ headless }); + const normalizedEngine = String(engine).toLowerCase() === "firefox" ? "firefox" : "chromium"; + const browserType = normalizedEngine === "firefox" ? firefox : chromium; + const executablePath = resolveSystemBrowser(normalizedEngine); + const options = { + headless, + timeout: 10_000, + ...(executablePath ? { executablePath } : {}), + }; + + return browserType.launch(options).catch((error) => { + if (normalizedEngine !== "firefox") throw error; + + const chromiumPath = resolveSystemBrowser("chromium"); + if (!chromiumPath) throw error; + return chromium.launch({ headless, timeout: 10_000, executablePath: chromiumPath }); + }); +} + +function resolveSystemBrowser(engine) { + if (process.platform !== "win32") return ""; + + const candidates = engine === "firefox" + ? ["C:\\Program Files\\Mozilla Firefox\\firefox.exe", "C:\\Program Files (x86)\\Mozilla Firefox\\firefox.exe"] + : [ + "C:\\Program Files\\Google\\Chrome\\Application\\chrome.exe", + "C:\\Program Files (x86)\\Google\\Chrome\\Application\\chrome.exe", + "C:\\Program Files (x86)\\Microsoft\\Edge\\Application\\msedge.exe", + ]; + + return candidates.find((candidate) => fs.existsSync(candidate)) || ""; } export async function closeVisibleBrowsers() {