fix(smartpdf): lazily initialize SmartPdf, stop it only when present, and make evaluateOnPage reliably close pages
This commit is contained in:
34
ts/index.ts
34
ts/index.ts
@@ -14,16 +14,28 @@ export class SmartBrowser {
|
||||
*/
|
||||
public async start() {
|
||||
this.headlessBrowser = await plugins.smartpuppeteer.getEnvAwareBrowserInstance();
|
||||
this.smartpdf = new plugins.smartpdf.SmartPdf();
|
||||
await this.smartpdf.start(this.headlessBrowser);
|
||||
// SmartPdf is lazy-initialized only when PDF methods are called
|
||||
}
|
||||
|
||||
/**
|
||||
* ensure SmartPdf is initialized (lazy)
|
||||
*/
|
||||
private async ensureSmartPdf() {
|
||||
if (!this.smartpdf) {
|
||||
this.smartpdf = new plugins.smartpdf.SmartPdf();
|
||||
await this.smartpdf.start(this.headlessBrowser);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* stop the SmartBrowser instance
|
||||
*/
|
||||
public async stop() {
|
||||
if (this.smartpdf) {
|
||||
await this.smartpdf.stop();
|
||||
this.smartpdf = null;
|
||||
}
|
||||
await this.headlessBrowser.close();
|
||||
await this.smartpdf.stop();
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -31,6 +43,7 @@ export class SmartBrowser {
|
||||
* @param urlArg
|
||||
*/
|
||||
public async pdfFromPage(urlArg: string): Promise<plugins.smartpdf.IPdf> {
|
||||
await this.ensureSmartPdf();
|
||||
const result = await this.smartpdf.getFullWebsiteAsSinglePdf(urlArg);
|
||||
return result;
|
||||
}
|
||||
@@ -63,12 +76,15 @@ export class SmartBrowser {
|
||||
*/
|
||||
public async evaluateOnPage<T>(urlArg: string, funcArg: () => Promise<T>) {
|
||||
const page = await this.headlessBrowser.newPage();
|
||||
await page.goto(urlArg, {
|
||||
waitUntil: 'networkidle2',
|
||||
});
|
||||
const result = await page.evaluate(funcArg);
|
||||
await page.close();
|
||||
return result;
|
||||
try {
|
||||
await page.goto(urlArg, {
|
||||
waitUntil: 'networkidle2',
|
||||
});
|
||||
const result = await page.evaluate(funcArg);
|
||||
return result;
|
||||
} finally {
|
||||
try { await page.close(); } catch (e) { /* page may already be closed */ }
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
Reference in New Issue
Block a user