-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.mjs
87 lines (70 loc) · 2.67 KB
/
index.mjs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
import puppeteer from 'puppeteer';
import { Response } from 'node-fetch';
import fs from 'fs';
export default {
async fetch(request, env) {
console.log("Starting the fetch function");
const browser = await puppeteer.launch();
const page = await browser.newPage();
await page.setViewport({
width: 1280,
height: 800,
});
console.log(`Navigating to ${env.GITHUB_URL}`);
await page.goto(env.GITHUB_URL, { waitUntil: 'networkidle2' });
let yearlyContributions;
try {
yearlyContributions = await page.$eval('.js-yearly-contributions h2', el => el.innerText);
console.log('Yearly contributions:', yearlyContributions);
} catch (error) {
console.log("The page isn't available");
yearlyContributions = "The page isn't available";
}
console.log("Injecting custom HTML content");
const customHtmlContent = `
<div id="custom-content" style="margin-top: 20px; text-align: center; padding: 20px;">
<h1>Screenshot of My yearly contributions</h1>
<h2>Yearly contributions are: ${yearlyContributions}</h2>
</div>
`;
await page.evaluate((html) => {
const customContentDiv = document.createElement('div');
customContentDiv.innerHTML = html;
document.body.prepend(customContentDiv);
}, customHtmlContent);
console.log("Taking screenshot");
const screenshot = await page.screenshot({ encoding: 'base64', fullPage: true });
fs.writeFileSync('screenshot.png', Buffer.from(screenshot, 'base64'));
console.log("Screenshot saved as screenshot.png");
console.log(`Screenshot Base64 length: ${screenshot.length}`);
console.log("Closing browser");
await browser.close();
console.log("Returning response");
const responseHtml = `
<!DOCTYPE html>
<html>
<head>
<title>Screenshot of My yearly contributions</title>
</head>
<body>
<h1>Screenshot of My yearly contributions</h1>
<img src='data:image/png;base64,${screenshot}' />
</body>
</html>
`;
return new Response(responseHtml, {
headers: {
'Content-Type': 'text/html',
}
});
}
};
// To test the function
(async () => {
const env = {
GITHUB_URL: 'https://github.com/irinakalman'
};
const request = {}; // Mock request object
const response = await (await import('./index.mjs')).default.fetch(request, env);
// console.log(await response.text());
})();