smartbrowser/ts/index.ts

74 lines
1.8 KiB
TypeScript
Raw Normal View History

2022-03-24 13:57:16 +00:00
import * as plugins from './smartbrowser.plugins.js';
2016-09-19 18:00:19 +00:00
2022-03-24 13:57:16 +00:00
import * as interfaces from './interfaces/index.js';
2019-06-03 15:16:47 +00:00
/**
* SmartBrowser
*/
2019-05-29 06:57:17 +00:00
export class SmartBrowser {
2019-06-04 06:29:05 +00:00
public headlessBrowser: plugins.smartpuppeteer.puppeteer.Browser;
2019-06-03 15:16:47 +00:00
public smartpdf: plugins.smartpdf.SmartPdf;
2019-06-04 06:29:05 +00:00
/**
* start the SmartBrowser instance
*/
public async start() {
this.headlessBrowser = await plugins.smartpuppeteer.getEnvAwareBrowserInstance();
this.smartpdf = new plugins.smartpdf.SmartPdf();
await this.smartpdf.start(this.headlessBrowser);
}
/**
* stop the SmartBrowser instance
*/
public async stop() {
await this.headlessBrowser.close();
await this.smartpdf.stop();
}
2019-06-03 15:16:47 +00:00
/**
* create a pdf from page
* @param urlArg
*/
2022-11-08 06:56:52 +00:00
public async pdfFromPage(urlArg: string): Promise<plugins.smartpdf.IPdf> {
2022-03-25 00:19:21 +00:00
const result = await this.smartpdf.getFullWebsiteAsSinglePdf(urlArg);
2019-06-03 15:16:47 +00:00
return result;
}
/**
* make a screenshot from a page
2019-06-03 15:17:20 +00:00
* @param urlArg
2019-06-03 15:16:47 +00:00
*/
public async screenshotFromPage(urlArg: string): Promise<interfaces.IScreenShotResult> {
const pageId = plugins.smartunique.shortId();
const page = await this.headlessBrowser.newPage();
await page.goto(urlArg, {
2021-04-29 14:52:28 +00:00
waitUntil: 'networkidle2',
2019-06-03 15:16:47 +00:00
});
2023-09-11 08:18:45 +00:00
const screenshotBuffer = (await page.screenshot({
2021-04-29 14:52:28 +00:00
encoding: 'binary',
2023-09-11 08:18:45 +00:00
})) as Buffer;
2019-06-03 15:16:47 +00:00
await page.close();
return {
name: pageId,
id: `${pageId}.js`,
2021-04-29 14:52:28 +00:00
buffer: screenshotBuffer,
2019-06-03 15:16:47 +00:00
};
2019-05-29 12:14:26 +00:00
}
2019-06-03 15:16:47 +00:00
/**
* evalutes an expression on a page
2019-06-03 15:17:20 +00:00
* @param urlArg
* @param funcArg
2019-06-03 15:16:47 +00:00
*/
2020-06-01 20:19:25 +00:00
public async evaluateOnPage<T>(urlArg: string, funcArg: () => Promise<T>) {
2019-06-03 15:16:47 +00:00
const page = await this.headlessBrowser.newPage();
await page.goto(urlArg, {
2021-04-29 14:52:28 +00:00
waitUntil: 'networkidle2',
2019-06-03 15:16:47 +00:00
});
2020-06-01 20:19:25 +00:00
const result = await page.evaluate(funcArg);
await page.close();
return result;
2019-06-03 15:16:47 +00:00
}
2019-05-29 06:57:17 +00:00
}