fix: improve error handling in CF bypass to prevent server crashes
This commit is contained in:
1 parent
c565351c2f
commit
7137b046d7
1 file changed
+31
-23
@@ -7,32 +7,38 @@ let browser: any = null;
|
||||
|
||||
async function getBrowser() {
|
||||
if (browser) return browser;
|
||||
const puppeteer = await import("puppeteer-extra");
|
||||
const StealthPlugin = await import("puppeteer-extra-plugin-stealth");
|
||||
puppeteer.default.use(StealthPlugin.default());
|
||||
browser = await puppeteer.default.launch({
|
||||
headless: true,
|
||||
args: [
|
||||
"--no-sandbox",
|
||||
"--disable-setuid-sandbox",
|
||||
"--disable-web-security",
|
||||
"--disable-blink-features=AutomationControlled",
|
||||
"--user-agent=" + UA,
|
||||
],
|
||||
});
|
||||
return browser;
|
||||
try {
|
||||
const puppeteer = await import("puppeteer-extra");
|
||||
const StealthPlugin = await import("puppeteer-extra-plugin-stealth");
|
||||
puppeteer.default.use(StealthPlugin.default());
|
||||
browser = await puppeteer.default.launch({
|
||||
headless: true,
|
||||
args: [
|
||||
"--no-sandbox",
|
||||
"--disable-setuid-sandbox",
|
||||
"--disable-web-security",
|
||||
"--disable-blink-features=AutomationControlled",
|
||||
"--user-agent=" + UA,
|
||||
],
|
||||
});
|
||||
return browser;
|
||||
} catch (e) {
|
||||
throw new Error(`Cloudflare bypass unavailable: ${(e as Error).message}`);
|
||||
}
|
||||
}
|
||||
|
||||
export async function fetchWithCfBypass(
|
||||
url: string,
|
||||
timeout = 30000,
|
||||
): Promise<string> {
|
||||
const b = await getBrowser();
|
||||
const page = await b.newPage();
|
||||
await page.setUserAgent(UA);
|
||||
await page.setDefaultTimeout(timeout);
|
||||
|
||||
let b: any;
|
||||
let page: any;
|
||||
try {
|
||||
b = await getBrowser();
|
||||
page = await b.newPage();
|
||||
await page.setUserAgent(UA);
|
||||
await page.setDefaultTimeout(timeout);
|
||||
|
||||
const response = await page.goto(url, {
|
||||
waitUntil: "networkidle2",
|
||||
timeout,
|
||||
@@ -66,10 +72,12 @@ export async function fetchWithCfBypass(
|
||||
const finalBody = await page.content();
|
||||
return finalBody;
|
||||
} finally {
|
||||
try {
|
||||
await page.close();
|
||||
} catch {
|
||||
// ignore cleanup errors
|
||||
if (page) {
|
||||
try {
|
||||
await page.close();
|
||||
} catch {
|
||||
// ignore cleanup errors
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
Reference in new issue
Block a user