-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathindex.js
More file actions
620 lines (561 loc) · 24.5 KB
/
index.js
File metadata and controls
620 lines (561 loc) · 24.5 KB
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
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
const express = require('express');
const puppeteer = require('puppeteer-core');
const { KnownDevices } = require('puppeteer-core');
const app = express();
app.use(express.json());
const PORT = process.env.PORT || 3000;
const BROWSER_WS_ENDPOINT = process.env.BROWSER_WS_ENDPOINT || 'ws://browser:3000';
const API_SECRET = process.env.API_SECRET;
app.get('/', (req, res) => {
const requiresAuth = !!API_SECRET;
res.send(`
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Webpage Screenshot API</title>
<style>
* {
margin: 0;
padding: 0;
box-sizing: border-box;
}
body {
font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, Helvetica, Arial, sans-serif;
background-color: #0f172a;
color: #f8fafc;
min-height: 100vh;
padding: 2rem;
}
.container {
max-width: 1200px;
margin: 0 auto;
}
h1 {
font-size: 2.5rem;
margin-bottom: 0.5rem;
background: linear-gradient(to right, #60a5fa, #a855f7);
-webkit-background-clip: text;
-webkit-text-fill-color: transparent;
text-align: center;
}
.subtitle {
text-align: center;
color: #94a3b8;
margin-bottom: 2rem;
}
.main-content {
display: grid;
grid-template-columns: 1fr 1fr;
gap: 2rem;
margin-top: 2rem;
}
.form-section, .result-section {
background-color: #1e293b;
border-radius: 12px;
padding: 2rem;
box-shadow: 0 4px 6px rgba(0, 0, 0, 0.1);
}
.form-group {
margin-bottom: 1.5rem;
}
label {
display: block;
margin-bottom: 0.5rem;
color: #cbd5e1;
font-weight: 500;
}
input, select {
width: 100%;
padding: 0.75rem;
background-color: #334155;
border: 1px solid #475569;
border-radius: 6px;
color: #f8fafc;
font-size: 1rem;
}
input:focus, select:focus {
outline: none;
border-color: #3b82f6;
}
input:disabled {
opacity: 0.5;
cursor: not-allowed;
}
.checkbox-group {
display: flex;
align-items: center;
gap: 0.5rem;
}
.checkbox-group input[type="checkbox"] {
width: auto;
cursor: pointer;
}
.btn {
width: 100%;
padding: 0.75rem 1.5rem;
background-color: #3b82f6;
color: white;
border: none;
border-radius: 6px;
font-weight: 600;
font-size: 1rem;
cursor: pointer;
transition: all 0.2s;
}
.btn:hover:not(:disabled) {
background-color: #2563eb;
transform: translateY(-1px);
}
.btn:disabled {
opacity: 0.5;
cursor: not-allowed;
}
.result-section h2 {
color: #f8fafc;
margin-bottom: 1rem;
}
.screenshot-container {
background-color: #334155;
border-radius: 8px;
padding: 1rem;
min-height: 400px;
display: flex;
align-items: center;
justify-content: center;
}
.screenshot-container img {
max-width: 100%;
height: auto;
border-radius: 4px;
}
.placeholder {
color: #64748b;
text-align: center;
}
.loading {
text-align: center;
color: #60a5fa;
}
.spinner {
border: 3px solid #334155;
border-top: 3px solid #60a5fa;
border-radius: 50%;
width: 40px;
height: 40px;
animation: spin 1s linear infinite;
margin: 0 auto 1rem;
}
@keyframes spin {
0% { transform: rotate(0deg); }
100% { transform: rotate(360deg); }
}
.error {
background-color: #7f1d1d;
color: #fecaca;
padding: 1rem;
border-radius: 6px;
margin-bottom: 1rem;
}
.info-badge {
display: inline-block;
background-color: #065f46;
color: #6ee7b7;
padding: 0.25rem 0.75rem;
border-radius: 9999px;
font-size: 0.875rem;
margin-left: 0.5rem;
}
@media (max-width: 768px) {
.main-content {
grid-template-columns: 1fr;
}
}
</style>
</head>
<body>
<div class="container">
<h1>📸 Webpage Screenshot API</h1>
<p class="subtitle">Generate pixel-perfect screenshots of any webpage</p>
<div class="main-content">
<div class="form-section">
<h2>Screenshot Settings</h2>
<form id="screenshotForm">
<div class="form-group">
<label for="url">URL *</label>
<input type="url" id="url" name="url" placeholder="https://www.google.com" required>
</div>
${requiresAuth ? `
<div class="form-group">
<label for="apiSecret">API Secret Key *</label>
<input type="password" id="apiSecret" name="apiSecret" placeholder="Enter your API secret" required>
</div>
` : `
<div class="form-group">
<label>API Secret Key <span class="info-badge">Not Required</span></label>
<input type="password" id="apiSecret" name="apiSecret" placeholder="No secret key required" disabled>
</div>
`}
<div class="form-group">
<label for="device">Device Emulation</label>
<select id="device" name="device">
<option value="">Custom Size</option>
<option value="iPhone 13">iPhone 13</option>
<option value="iPhone 13 Pro">iPhone 13 Pro</option>
<option value="iPhone 13 Pro Max">iPhone 13 Pro Max</option>
<option value="iPhone 12">iPhone 12</option>
<option value="iPhone 12 Pro">iPhone 12 Pro</option>
<option value="iPhone SE">iPhone SE</option>
<option value="iPad Pro" selected>iPad Pro</option>
<option value="iPad Mini">iPad Mini</option>
<option value="iPad">iPad</option>
<option value="Galaxy S9+">Galaxy S9+</option>
<option value="Galaxy S20">Galaxy S20</option>
<option value="Pixel 5">Pixel 5</option>
</select>
</div>
<div class="form-group" id="customSizeGroup">
<label for="width">Width (px)</label>
<input type="number" id="width" name="width" placeholder="1280" value="1280">
</div>
<div class="form-group" id="customHeightGroup">
<label for="height">Height (px)</label>
<input type="number" id="height" name="height" placeholder="800" value="800">
</div>
<div class="form-group">
<label for="delay">Delay (ms)</label>
<input type="number" id="delay" name="delay" placeholder="0" min="0">
</div>
<div class="form-group">
<label for="waitForSelector">Wait for CSS Selector (optional)</label>
<input type="text" id="waitForSelector" name="waitForSelector" placeholder=".main-content">
</div>
<div class="form-group checkbox-group">
<input type="checkbox" id="fullPage" name="fullPage">
<label for="fullPage">Full Page Screenshot</label>
</div>
<div class="form-group checkbox-group">
<input type="checkbox" id="darkMode" name="darkMode">
<label for="darkMode">Dark Mode</label>
</div>
<button type="submit" class="btn" id="submitBtn">Generate Screenshot</button>
</form>
</div>
<div class="result-section">
<h2>Result</h2>
<div id="errorContainer"></div>
<div class="screenshot-container" id="screenshotContainer">
<div class="placeholder">Your screenshot will appear here</div>
</div>
</div>
</div>
</div>
<script>
const form = document.getElementById('screenshotForm');
const deviceSelect = document.getElementById('device');
const customSizeGroup = document.getElementById('customSizeGroup');
const customHeightGroup = document.getElementById('customHeightGroup');
const screenshotContainer = document.getElementById('screenshotContainer');
const errorContainer = document.getElementById('errorContainer');
const submitBtn = document.getElementById('submitBtn');
const requiresAuth = ${requiresAuth};
// Toggle custom size inputs based on device selection
deviceSelect.addEventListener('change', () => {
const isCustom = deviceSelect.value === '';
customSizeGroup.style.display = isCustom ? 'block' : 'none';
customHeightGroup.style.display = isCustom ? 'block' : 'none';
});
form.addEventListener('submit', async (e) => {
e.preventDefault();
// Clear previous errors
errorContainer.innerHTML = '';
// Show loading state
submitBtn.disabled = true;
submitBtn.textContent = 'Generating...';
screenshotContainer.innerHTML = \`
<div class="loading">
<div class="spinner"></div>
<p>Taking screenshot...</p>
</div>
\`;
// Collect form data
const formData = new FormData(form);
const data = {
url: formData.get('url'),
fullPage: formData.get('fullPage') === 'on',
darkMode: formData.get('darkMode') === 'on'
};
// Add optional fields
const device = formData.get('device');
if (device) {
data.device = device;
} else {
const width = formData.get('width');
const height = formData.get('height');
if (width) data.width = parseInt(width);
if (height) data.height = parseInt(height);
}
const delay = formData.get('delay');
if (delay) data.delay = parseInt(delay);
const waitForSelector = formData.get('waitForSelector');
if (waitForSelector) data.waitForSelector = waitForSelector;
try {
// Prepare headers
const headers = {
'Content-Type': 'application/json'
};
// Add API secret if required
if (requiresAuth) {
const apiSecret = formData.get('apiSecret');
if (apiSecret) {
headers['X-API-Secret'] = apiSecret;
}
}
const response = await fetch('/screenshot', {
method: 'POST',
headers: headers,
body: JSON.stringify(data)
});
const result = await response.json();
if (response.ok && result.success) {
screenshotContainer.innerHTML = \`
<img src="data:image/png;base64,\${result.screenshot}" alt="Screenshot" />
\`;
} else {
throw new Error(result.error || result.details || 'Failed to generate screenshot');
}
} catch (error) {
console.error('Error:', error);
errorContainer.innerHTML = \`
<div class="error">
<strong>Error:</strong> \${error.message}
</div>
\`;
screenshotContainer.innerHTML = \`
<div class="placeholder">Failed to generate screenshot. Please try again.</div>
\`;
} finally {
submitBtn.disabled = false;
submitBtn.textContent = 'Generate Screenshot';
}
});
// Initialize custom size visibility
deviceSelect.dispatchEvent(new Event('change'));
</script>
</body>
</html>
`);
});
app.post('/screenshot', async (req, res) => {
// 0. Security Check
if (API_SECRET) {
// req.get() is case-insensitive
const clientSecret = req.get('X-API-Secret');
if (clientSecret !== API_SECRET) {
return res.status(401).json({ error: 'Unauthorized: Invalid or missing API secret' });
}
}
let {
url,
width,
height,
device,
fullPage,
darkMode,
delay,
waitForSelector
} = req.body;
if (!url) {
return res.status(400).json({ error: 'URL is required' });
}
// If user doesn't specify device, width, or height, default to iPad Pro
const hasCustomSize = width || height;
const hasDeviceParam = device !== undefined;
if (!hasDeviceParam && !hasCustomSize) {
device = 'iPad Pro';
}
let browser;
try {
console.log(`Connecting to browser at ${BROWSER_WS_ENDPOINT}...`);
browser = await puppeteer.connect({
browserWSEndpoint: BROWSER_WS_ENDPOINT,
});
const page = await browser.newPage();
// 1. Device Emulation or Manual Viewport
if (device && KnownDevices[device]) {
console.log(`Emulating device: ${device}`);
await page.emulate(KnownDevices[device]);
} else {
// Set realistic user agent for custom sizes
const viewport = {
width: parseInt(width) || 1280,
height: parseInt(height) || 800,
deviceScaleFactor: 2,
hasTouch: false,
isLandscape: false,
isMobile: false
};
await page.setViewport(viewport);
// Set realistic desktop browser user agent
await page.setUserAgent('Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36');
}
// Anti-bot detection: Remove webdriver flags and set realistic properties
await page.evaluateOnNewDocument(() => {
// Remove webdriver property
Object.defineProperty(navigator, 'webdriver', {
get: () => false,
});
// Override the plugins property to add realistic plugins
Object.defineProperty(navigator, 'plugins', {
get: () => [
{
0: {type: "application/x-google-chrome-pdf", suffixes: "pdf", description: "Portable Document Format"},
description: "Portable Document Format",
filename: "internal-pdf-viewer",
length: 1,
name: "Chrome PDF Plugin"
},
{
0: {type: "application/pdf", suffixes: "pdf", description: ""},
description: "",
filename: "mhjfbmdgcfjbbpaeojofohoefgiehjai",
length: 1,
name: "Chrome PDF Viewer"
},
{
0: {type: "application/x-nacl"},
description: "Native Client Executable",
filename: "internal-nacl-plugin",
length: 2,
name: "Native Client"
}
],
});
// Override languages
Object.defineProperty(navigator, 'languages', {
get: () => ['en-US', 'en'],
});
// Chrome runtime
window.chrome = {
runtime: {},
loadTimes: function() {},
csi: function() {},
app: {}
};
// Permissions
const originalQuery = window.navigator.permissions.query;
window.navigator.permissions.query = (parameters) => (
parameters.name === 'notifications' ?
Promise.resolve({ state: Notification.permission }) :
originalQuery(parameters)
);
// Override hardware concurrency
Object.defineProperty(navigator, 'hardwareConcurrency', {
get: () => 8,
});
// Override device memory
Object.defineProperty(navigator, 'deviceMemory', {
get: () => 8,
});
// Override platform
Object.defineProperty(navigator, 'platform', {
get: () => 'MacIntel',
});
// Mock screen properties
Object.defineProperty(screen, 'availWidth', {
get: () => 1920,
});
Object.defineProperty(screen, 'availHeight', {
get: () => 1080,
});
Object.defineProperty(screen, 'width', {
get: () => 1920,
});
Object.defineProperty(screen, 'height', {
get: () => 1080,
});
// WebGL vendor and renderer
const getParameter = WebGLRenderingContext.prototype.getParameter;
WebGLRenderingContext.prototype.getParameter = function(parameter) {
if (parameter === 37445) {
return 'Intel Inc.';
}
if (parameter === 37446) {
return 'Intel Iris OpenGL Engine';
}
return getParameter.apply(this, [parameter]);
};
// Add realistic fonts
const originalFonts = Object.getOwnPropertyDescriptor(Document.prototype, 'fonts');
if (originalFonts) {
Object.defineProperty(Document.prototype, 'fonts', {
get: function() {
const fonts = originalFonts.get.call(this);
// Mock common system fonts
return fonts;
}
});
}
});
// Set extra HTTP headers to mimic real browser
await page.setExtraHTTPHeaders({
'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8',
'Accept-Encoding': 'gzip, deflate, br',
'Accept-Language': 'en-US,en;q=0.9',
'Sec-Fetch-Dest': 'document',
'Sec-Fetch-Mode': 'navigate',
'Sec-Fetch-Site': 'none',
'Sec-Fetch-User': '?1',
'Upgrade-Insecure-Requests': '1'
});
// 2. Dark Mode
if (darkMode) {
console.log('Enabling Dark Mode');
await page.emulateMediaFeatures([
{ name: 'prefers-color-scheme', value: 'dark' }
]);
}
console.log(`Navigating to ${url}...`);
await page.goto(url, {
waitUntil: 'networkidle0',
timeout: 30000
});
// 3. Post-load Waits
if (waitForSelector) {
console.log(`Waiting for selector: ${waitForSelector}`);
try {
await page.waitForSelector(waitForSelector, { timeout: 10000 });
} catch (e) {
console.warn(`Timeout waiting for selector: ${waitForSelector}`);
}
}
if (delay) {
console.log(`Waiting for ${delay}ms delay...`);
await new Promise(r => setTimeout(r, parseInt(delay)));
}
console.log('Taking screenshot...');
const screenshot = await page.screenshot({
encoding: 'base64',
fullPage: !!fullPage
});
await page.close();
res.json({
success: true,
screenshot: screenshot
});
} catch (error) {
console.error('Error taking screenshot:', error);
res.status(500).json({
error: 'Failed to take screenshot',
details: error.message
});
} finally {
if (browser) {
browser.disconnect();
}
}
});
app.listen(PORT, () => {
console.log(`Screenshot API listening on port ${PORT}`);
});