smartbrowser/ts/index.ts

76 lines
1.9 KiB
TypeScript
Raw Permalink Normal View History

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