fix: improve error handling in CF bypass to prevent server crashes
This commit is contained in:
1 parent
c565351c2f
commit
7137b046d7
1 file changed
+11
-3
@@ -7,6 +7,7 @@ let browser: any = null;
|
|||||||
|
|
||||||
async function getBrowser() {
|
async function getBrowser() {
|
||||||
if (browser) return browser;
|
if (browser) return browser;
|
||||||
|
try {
|
||||||
const puppeteer = await import("puppeteer-extra");
|
const puppeteer = await import("puppeteer-extra");
|
||||||
const StealthPlugin = await import("puppeteer-extra-plugin-stealth");
|
const StealthPlugin = await import("puppeteer-extra-plugin-stealth");
|
||||||
puppeteer.default.use(StealthPlugin.default());
|
puppeteer.default.use(StealthPlugin.default());
|
||||||
@@ -21,18 +22,23 @@ async function getBrowser() {
|
|||||||
],
|
],
|
||||||
});
|
});
|
||||||
return browser;
|
return browser;
|
||||||
|
} catch (e) {
|
||||||
|
throw new Error(`Cloudflare bypass unavailable: ${(e as Error).message}`);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
export async function fetchWithCfBypass(
|
export async function fetchWithCfBypass(
|
||||||
url: string,
|
url: string,
|
||||||
timeout = 30000,
|
timeout = 30000,
|
||||||
): Promise<string> {
|
): Promise<string> {
|
||||||
const b = await getBrowser();
|
let b: any;
|
||||||
const page = await b.newPage();
|
let page: any;
|
||||||
|
try {
|
||||||
|
b = await getBrowser();
|
||||||
|
page = await b.newPage();
|
||||||
await page.setUserAgent(UA);
|
await page.setUserAgent(UA);
|
||||||
await page.setDefaultTimeout(timeout);
|
await page.setDefaultTimeout(timeout);
|
||||||
|
|
||||||
try {
|
|
||||||
const response = await page.goto(url, {
|
const response = await page.goto(url, {
|
||||||
waitUntil: "networkidle2",
|
waitUntil: "networkidle2",
|
||||||
timeout,
|
timeout,
|
||||||
@@ -66,6 +72,7 @@ export async function fetchWithCfBypass(
|
|||||||
const finalBody = await page.content();
|
const finalBody = await page.content();
|
||||||
return finalBody;
|
return finalBody;
|
||||||
} finally {
|
} finally {
|
||||||
|
if (page) {
|
||||||
try {
|
try {
|
||||||
await page.close();
|
await page.close();
|
||||||
} catch {
|
} catch {
|
||||||
@@ -73,6 +80,7 @@ export async function fetchWithCfBypass(
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
}
|
||||||
|
|
||||||
export async function fetchJsonWithCfBypass<T = unknown>(
|
export async function fetchJsonWithCfBypass<T = unknown>(
|
||||||
url: string,
|
url: string,
|
||||||
|
|||||||
Reference in new issue
Block a user