2024-05-06 22:51:32 +02:00
|
|
|
import puppeteer from 'puppeteer-core';
|
|
|
|
import chromium from 'chrome-aws-lambda';
|
|
|
|
import middleware from './_common/middleware.js';
|
2023-07-22 01:05:09 +02:00
|
|
|
|
2024-05-06 22:51:32 +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-09-12 11:01:49 +02:00
|
|
|
args: [...chromium.args, '--no-sandbox'], // Add --no-sandbox flag
|
2023-07-22 01:05:09 +02:00
|
|
|
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
|
|
|
|
2024-05-06 22:51:32 +02:00
|
|
|
export const handler = middleware(screenshotHandler);
|
|
|
|
export default handler;
|