-
Notifications
You must be signed in to change notification settings - Fork 434
Expand file tree
/
Copy pathrun-javascript-headless-browser.mjs
More file actions
executable file
·87 lines (76 loc) · 2.36 KB
/
run-javascript-headless-browser.mjs
File metadata and controls
executable file
·87 lines (76 loc) · 2.36 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
import fs from 'node:fs';
let chromium;
try {
({ chromium } = await import('playwright'));
} catch (playwrightError) {
try {
({ chromium } = await import('@playwright/test'));
} catch (playwrightTestError) {
console.error('Unable to load Playwright. Install either "playwright" or "@playwright/test".');
console.error('Import from "playwright" failed:', String(playwrightError));
console.error('Import from "@playwright/test" failed:', String(playwrightTestError));
process.exit(2);
}
}
const url = process.env.URL;
const logFile = process.env.LOG_FILE;
const timeoutSeconds = Number(process.env.CN1_JS_BROWSER_LIFETIME_SECONDS || '120');
if (!url) {
console.error('URL is required');
process.exit(2);
}
const SUITE_FINISHED_MARKER = 'CN1SS:SUITE:FINISHED';
let suiteFinished = false;
function append(line) {
const text = `[playwright] ${line}\n`;
if (logFile) {
fs.appendFileSync(logFile, text, 'utf8');
} else {
process.stdout.write(text);
}
}
const browser = await chromium.launch({
headless: true,
args: [
'--autoplay-policy=no-user-gesture-required',
'--disable-web-security',
'--allow-file-access-from-files'
]
});
try {
const page = await browser.newPage({
viewport: { width: 1280, height: 900 }
});
page.on('console', msg => {
const text = msg.text();
append(`console:${msg.type()}:${text}`);
if (text.indexOf(SUITE_FINISHED_MARKER) >= 0) {
suiteFinished = true;
}
});
page.on('pageerror', err => append(`pageerror:${String(err)}`));
page.on('requestfailed', req => append(`requestfailed:${req.url()} ${req.failure()?.errorText || ''}`));
page.on('response', resp => {
if (resp.status() >= 400) {
append(`response:${resp.status()}:${resp.url()}`);
}
});
append(`goto:${url}`);
await page.goto(url, { waitUntil: 'domcontentloaded', timeout: 60000 });
await page.waitForTimeout(2000);
const start = Date.now();
while (Date.now() - start < timeoutSeconds * 1000) {
const state = await page.evaluate(() => ({
initialized: !!window.cn1Initialized,
started: !!window.cn1Started,
error: window.__parparError ? JSON.stringify(window.__parparError) : ''
}));
append(`state:${JSON.stringify(state)}`);
if (state.error || suiteFinished) {
break;
}
await page.waitForTimeout(1000);
}
} finally {
await browser.close();
}