Skip to content
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
31 changes: 29 additions & 2 deletions packages/core/src/infrastructure/puppeteer.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,8 @@
import puppeteer, { type Browser, type Page } from 'puppeteer-core';
import puppeteer, {
type Browser,
type Page,
TimeoutError,
} from 'puppeteer-core';
import UserAgent from 'user-agents';

// Environment Variable(s)
Expand Down Expand Up @@ -30,13 +34,14 @@ export async function getPageContent(url: string): Promise<string> {
waitUntil: 'domcontentloaded',
});

await page.waitForNetworkIdle();
const idleTimedOut = await waitForIdleOrContinue(page);

const content = await page.evaluate(() => {
return document.body.innerText;
});

console.log('Page content found.', {
idleTimedOut,
length: content.length,
status: response?.status(),
url: url.slice(0, 50) + '...',
Expand All @@ -48,6 +53,28 @@ export async function getPageContent(url: string): Promise<string> {

// Helpers

/**
* Waits up to 5 seconds for the network to go idle. Some sites never go idle
* (e.g. analytics, polling), so if we time out we keep going and read whatever
* has rendered. Any other error is rethrown.
*
* @param page - Page to wait on.
* @returns Whether the wait timed out.
*/
async function waitForIdleOrContinue(page: Page): Promise<boolean> {
try {
await page.waitForNetworkIdle({ timeout: 5_000 });

return false;
} catch (e) {
if (!(e instanceof TimeoutError)) {
throw e;
}

return true;
}
}

/**
* Runs the given function with a new Puppeteer browser instance and page
* instance. It sets a random user agent string for the page and closes the
Expand Down
Loading