2023-07-22 01:05:09 +02:00
|
|
|
const puppeteer = require('puppeteer-core');
|
2023-07-22 15:15:22 +02:00
|
|
|
const chromium = require('chrome-aws-lambda');
|
2023-08-09 23:33:36 +02:00
|
|
|
const middleware = require('./_common/middleware');
|
2023-07-22 01:05:09 +02:00
|
|
|
|
2023-08-09 23:33:36 +02:00
|
|
|
const screenshotHandler = async (targetUrl) => {
|
2023-07-22 01:05:09 +02:00
|
|
|
|
|
|
|
if (!targetUrl) {
|
2023-08-09 23:33:36 +02:00
|
|
|
throw new Error('URL is missing from queryStringParameters');
|
2023-07-22 01:05:09 +02:00
|
|
|
}
|
|
|
|
|
|
|
|
if (!targetUrl.startsWith('http://') && !targetUrl.startsWith('https://')) {
|
|
|
|
targetUrl = 'http://' + targetUrl;
|
|
|
|
}
|
|
|
|
|
|
|
|
try {
|
|
|
|
new URL(targetUrl);
|
|
|
|
} catch (error) {
|
2023-08-09 23:33:36 +02:00
|
|
|
throw new Error('URL provided is invalid');
|
2023-07-22 01:05:09 +02:00
|
|
|
}
|
|
|
|
|
2023-08-09 23:33:36 +02:00
|
|
|
let browser = null;
|
2023-07-22 01:05:09 +02:00
|
|
|
try {
|
2023-07-22 15:15:22 +02:00
|
|
|
browser = await puppeteer.launch({
|
2023-07-22 01:05:09 +02:00
|
|
|
args: chromium.args,
|
|
|
|
defaultViewport: { width: 800, height: 600 },
|
2023-07-22 16:18:28 +02:00
|
|
|
executablePath: process.env.CHROME_PATH || await chromium.executablePath,
|
2023-07-22 01:05:09 +02:00
|
|
|
headless: chromium.headless,
|
|
|
|
ignoreHTTPSErrors: true,
|
2023-07-22 16:18:28 +02:00
|
|
|
ignoreDefaultArgs: ['--disable-extensions'],
|
2023-07-22 01:05:09 +02:00
|
|
|
});
|
|
|
|
|
|
|
|
let page = await browser.newPage();
|
|
|
|
|
|
|
|
await page.emulateMediaFeatures([{ name: 'prefers-color-scheme', value: 'dark' }]);
|
2023-07-22 15:15:22 +02:00
|
|
|
page.setDefaultNavigationTimeout(8000);
|
2023-07-22 01:05:09 +02:00
|
|
|
await page.goto(targetUrl, { waitUntil: 'domcontentloaded' });
|
|
|
|
|
|
|
|
await page.evaluate(() => {
|
|
|
|
const selector = 'body';
|
|
|
|
return new Promise((resolve, reject) => {
|
|
|
|
const element = document.querySelector(selector);
|
|
|
|
if (!element) {
|
|
|
|
reject(new Error(`Error: No element found with selector: ${selector}`));
|
|
|
|
}
|
|
|
|
resolve();
|
|
|
|
});
|
|
|
|
});
|
|
|
|
|
|
|
|
const screenshotBuffer = await page.screenshot();
|
|
|
|
const base64Screenshot = screenshotBuffer.toString('base64');
|
|
|
|
|
2023-08-09 23:33:36 +02:00
|
|
|
return { image: base64Screenshot };
|
2023-07-22 01:05:09 +02:00
|
|
|
|
|
|
|
} finally {
|
|
|
|
if (browser !== null) {
|
|
|
|
await browser.close();
|
|
|
|
}
|
|
|
|
}
|
|
|
|
};
|
2023-08-09 23:33:36 +02:00
|
|
|
|
|
|
|
exports.handler = middleware(screenshotHandler);
|