-
Notifications
You must be signed in to change notification settings - Fork 0
/
puppeteer-tests.ts
executable file
·665 lines (574 loc) · 19.1 KB
/
puppeteer-tests.ts
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
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
import * as puppeteer from "puppeteer";
import { TimeoutError } from "puppeteer/Errors";
import * as Devices from "puppeteer/DeviceDescriptors";
// Accessibility
(async () => {
const browser = await puppeteer.launch();
const page = await browser.newPage();
const snap = await page.accessibility.snapshot({
interestingOnly: true,
root: undefined,
});
for (const child of snap.children) {
console.log(child.name);
}
});
// Basic nagivation
(async () => {
const browser = await puppeteer.launch();
const page = await browser.newPage();
await page.goto("https://example.com", {
referer: 'http://google.com',
});
await page.screenshot({ path: "example.png" });
browser.close();
})();
(async () => {
const browser = await puppeteer.launch();
const page = await browser.newPage();
page.setDefaultTimeout(100000);
await page.goto("https://news.ycombinator.com", { waitUntil: "networkidle0" });
await page.pdf({ path: "hn.pdf", format: "A4" });
const frame = page.frames()[0];
await frame.goto('/');
browser.close();
})();
(async () => {
const browser = await puppeteer.launch();
const page = await browser.newPage();
await page.goto("https://example.com");
// Get the "viewport" of the page, as reported by the page.
const dimensions = await page.evaluate(() => {
return {
// tslint:disable-next-line no-unnecessary-type-assertion
width: document.documentElement!.clientWidth,
// tslint:disable-next-line no-unnecessary-type-assertion
height: document.documentElement!.clientHeight,
deviceScaleFactor: window.devicePixelRatio
};
});
console.log("Dimensions:", dimensions);
browser.close();
})();
// The following examples are taken from the docs itself
puppeteer.launch().then(async browser => {
const page = await browser.newPage();
page.on("console", (...args: any[]) => {
for (let i = 0; i < args.length; ++i) console.log(`${i}: ${args[i]}`);
});
page.evaluate(() => console.log(5, "hello", { foo: "bar" }));
const result = await page.evaluate(() => {
return Promise.resolve(8 * 7);
});
console.log(await page.evaluate("1 + 2"));
const bodyHandle = await page.$("body");
// Typings for this are really difficult since they depend on internal state
// of the page class.
const html = await page.evaluate(
(body: HTMLElement) => body.innerHTML,
bodyHandle
);
});
import * as crypto from "crypto";
import * as fs from "fs";
puppeteer.launch().then(async browser => {
const page = await browser.newPage();
page.on("console", console.log);
await page.exposeFunction("md5", (text: string) =>
crypto
.createHash("md5")
.update(text)
.digest("hex")
);
await page.evaluate(async () => {
// use window.md5 to compute hashes
const myString = "PUPPETEER";
const myHash = await (window as any).md5(myString);
console.log(`md5 of ${myString} is ${myHash}`);
});
browser.close();
page.on("console", console.log);
await page.exposeFunction("readfile", async (filePath: string) => {
return new Promise((resolve, reject) => {
fs.readFile(filePath, "utf8", (err, text) => {
if (err) reject(err);
else resolve(text);
});
});
});
await page.evaluate(async () => {
// use window.readfile to read contents of a file
const content = await (window as any).readfile("/etc/hosts");
console.log(content);
});
await page.emulateMedia("screen");
await page.emulate(Devices['test']);
await page.emulate(puppeteer.devices['test']);
await page.pdf({ path: "page.pdf" });
await page.setRequestInterception(true);
page.on("request", interceptedRequest => {
if (
interceptedRequest.url().endsWith(".png") ||
interceptedRequest.url().endsWith(".jpg")
)
interceptedRequest.abort();
else interceptedRequest.continue({
headers: {
dope: 'yes',
}
});
});
page.keyboard.type("Hello"); // Types instantly
page.keyboard.type("World", { delay: 100 }); // Types slower, like a user
const watchDog = page.waitForFunction("window.innerWidth < 100");
page.setViewport({ width: 50, height: 50 });
await watchDog;
let currentURL: string;
page
.waitForSelector("img", { visible: true })
.then(() => console.log("First URL with image by selector: " + currentURL));
page
.waitForXPath("//img", { visible: true })
.then(() => console.log("First URL with image by xpath: " + currentURL));
for (currentURL of [
"https://example.com",
"https://google.com",
"https://bbc.com"
]) {
await page.goto(currentURL);
}
page.keyboard.type("Hello World!");
page.keyboard.press("ArrowLeft");
page.keyboard.down("Shift");
// tslint:disable-next-line prefer-for-of
for (let i = 0; i < " World".length; i++) {
page.keyboard.press("ArrowLeft");
}
page.keyboard.up("Shift");
page.keyboard.press("Backspace");
page.keyboard.sendCharacter("嗨");
await page.tracing.start({ path: "trace.json" });
await page.goto("https://www.google.com");
await page.tracing.stop();
page.on("dialog", async dialog => {
console.log(dialog.message());
await dialog.dismiss();
browser.close();
});
const inputElement = (await page.$("input[type=submit]"))!;
await inputElement.click();
});
// Example with launch options
(async () => {
const browser = await puppeteer.launch({
args: [
'--no-sandbox',
'--disable-setuid-sandbox',
],
defaultViewport: { width: 800, height: 600 },
handleSIGINT: true,
handleSIGHUP: true,
handleSIGTERM: true,
});
const page = await browser.newPage();
await page.goto("https://example.com");
await page.screenshot({ path: "example.png" });
browser.close();
})();
// Launching with default viewport disabled
(async () => {
await puppeteer.launch({
defaultViewport: null
});
})();
// Test v0.12 features
(async () => {
const browser = await puppeteer.launch({
devtools: true,
env: {
JEST_TEST: true
}
});
const page = await browser.newPage();
const button = (await page.$("#myButton"))!;
const div = (await page.$("#myDiv"))!;
const input = (await page.$("#myInput"))!;
if (!button)
throw new Error('Unable to select myButton');
if (!input)
throw new Error('Unable to select myInput');
await page.addStyleTag({
url: "https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css"
});
console.log(page.url());
page.type("#myInput", "Hello World!");
page.on("console", (event: puppeteer.ConsoleMessage, ...args: any[]) => {
console.log(event.text(), event.type(), event.location());
for (let i = 0; i < args.length; ++i) console.log(`${i}: ${args[i]}`);
});
await button.focus();
await button.press("Enter");
const screenshotOpts: puppeteer.BinaryScreenShotOptions = {
type: "jpeg",
omitBackground: true,
clip: {
x: 0,
y: 0,
width: 200,
height: 100
}
};
await button.screenshot(screenshotOpts);
console.log(button.toString());
input.type("Hello World", { delay: 10 });
const buttonText = await (await button.getProperty('textContent')).jsonValue();
await page.deleteCookie(...await page.cookies());
const metrics = await page.metrics();
console.log(metrics.Documents, metrics.Frames, metrics.JSEventListeners);
page.on('metrics', data => {
const title: string = data.title;
const metrics: puppeteer.Metrics = data.metrics;
});
const navResponse = await page.waitForNavigation({
timeout: 1000
});
console.log(navResponse.ok(), navResponse.status(), navResponse.url(), navResponse.headers()['Content-Type']);
// evaluate example
const bodyHandle = (await page.$('body'))!;
const html = await page.evaluate(body => body.innerHTML, bodyHandle);
await bodyHandle.dispose();
// getProperties example
const handle = await page.evaluateHandle(() => ({ window, document }));
const properties = await handle.getProperties();
const windowHandle = properties.get('window');
const documentHandle = properties.get('document');
await handle.dispose();
// queryObjects example
// Create a Map object
await page.evaluate(() => (window as any).map = new Map());
// Get a handle to the Map object prototype
const mapPrototype = await page.evaluateHandle(() => Map.prototype);
// Query all map instances into an array
const mapInstances = await page.queryObjects(mapPrototype);
// Count amount of map objects in heap
const count = await page.evaluate(maps => maps.length, mapInstances);
await mapInstances.dispose();
await mapPrototype.dispose();
// evaluateHandle example
const aHandle = await page.evaluateHandle(() => document.body);
const resultHandle = await page.evaluateHandle(body => body.innerHTML, aHandle);
console.log(await resultHandle.jsonValue());
await resultHandle.dispose();
browser.close();
})();
// test $eval and $$eval
(async () => {
const browser = await puppeteer.launch();
const page = await browser.newPage();
await page.goto("https://example.com");
const elementText = await page.$eval(
'#someElement',
(
element, // $ExpectType Element
) => {
element.innerHTML; // $ExpectType string
return element.innerHTML;
}
);
elementText; // $ExpectType string
// If one returns a DOM reference, puppeteer will wrap an ElementHandle instead
const someElement = await page.$$eval(
'.someClassName',
(
elements, // $ExpectType Element[]
) => {
console.log(elements.length);
console.log(elements[0].outerHTML);
return elements[3] as HTMLDivElement;
}
);
someElement; // $ExpectType ElementHandle<HTMLDivElement>
// If one passes an ElementHandle, puppeteer will unwrap its DOM reference instead
await page.$eval('.hello-world', (e, x1) => (x1 as any).noWrap, someElement);
browser.close();
})();
// Test request API
(async () => {
const browser = await puppeteer.launch();
const page = await browser.newPage();
const handler = async (r: puppeteer.Request) => {
const failure = r.failure();
console.log(r.headers().Test);
const response = r.response();
if (!response) {
return;
}
const text: string = response.statusText();
const ip: string = response.remoteAddress().ip;
const data = (await response.json()) as string;
const randomHeader = response.headers().Test;
if (failure == null) {
console.error("Request completed successfully");
return;
}
console.log("Request failed", failure.errorText.toUpperCase());
};
page.on('requestfinished', handler);
page.on('requestfailed', handler);
})();
// Test 1.0 features
(async () => {
const browser = await puppeteer.launch({
ignoreDefaultArgs: true,
});
const page = await browser.newPage();
const args: string[] = puppeteer.defaultArgs();
await page.pdf({
headerTemplate: 'header',
footerTemplate: 'footer',
});
await page.coverage.startCSSCoverage();
await page.coverage.startJSCoverage();
let cov = await page.coverage.stopCSSCoverage();
cov = await page.coverage.stopJSCoverage();
const text: string = cov[0].text;
const url: string = cov[0].url;
const firstRange: number = cov[0].ranges[0].end - cov[0].ranges[0].start;
let [handle]: puppeteer.ElementHandle[] = await page.$x('expression');
([handle] = await page.mainFrame().$x('expression'));
([handle] = await handle.$x('expression'));
const target = page.target();
const session = await target.createCDPSession();
await session.send('methodname', { option: 42 });
await session.detach();
await page.tracing.start({ path: "trace.json", categories: ["one", "two"] });
});
// 1.5: From the BrowserContext example
(async () => {
const browser = await puppeteer.launch();
// Create a new incognito browser context
const context = await browser.createIncognitoBrowserContext();
// Create a new page inside context.
const page = await context.newPage();
// ... do stuff with page ...
await page.goto('https://example.com');
// Dispose context once it's no longer needed.
await context.close();
});
// 1.5: From the Worker example
(async () => {
const browser = await puppeteer.launch();
const page = await browser.newPage();
page.on('workercreated', worker => console.log('Worker created: ' + worker.url()));
page.on('workerdestroyed', worker => console.log('Worker destroyed: ' + worker.url()));
console.log('Current workers:');
for (const worker of page.workers())
console.log(' ' + worker.url());
});
// Test conditional types
(async () => {
const browser = await puppeteer.launch();
const page = await browser.newPage();
const eh = await page.$('tr.something') as puppeteer.ElementHandle<HTMLTableRowElement>;
const index = await page.$eval(
'.demo',
(
e, // $ExpectType Element
x1, // $ExpectType HTMLTableRowElement
) => x1.rowIndex,
eh,
);
index; // $ExpectType number
});
// Test screenshot with an encoding option
(async () => {
const browser = await puppeteer.launch();
const page = await browser.newPage();
await page.goto("https://example.com");
const base64string: string = await page.screenshot({ encoding: "base64" });
const buffer: Buffer = await page.screenshot({ encoding: "binary" });
const screenshotOptions: puppeteer.ScreenshotOptions = {
fullPage: true,
};
const stringOrBuffer: string | Buffer = await page.screenshot(screenshotOptions);
browser.close();
})();
// Test waitFor
(async () => {
const browser = await puppeteer.launch();
const page = await browser.newPage();
await page.waitFor(1000); // $ExpectType void
const el: puppeteer.ElementHandle = await page.waitFor('selector');
const nullableEl: puppeteer.ElementHandle | null = await page.waitFor('selector', {
hidden: true,
});
const el2: puppeteer.ElementHandle = await page.waitFor('selector', {
timeout: 123,
});
await page.waitFor(() => !!document.querySelector('.foo'), {
hidden: true,
});
await page.waitFor((stuff: string) => !!document.querySelector(stuff), {
hidden: true,
}, 'asd');
const frame: puppeteer.Frame = page.frames()[0];
await frame.waitFor((stuff: string) => !!document.querySelector(stuff), {
hidden: true,
}, 'asd');
})();
// Permission tests
(async () => {
const browser = await puppeteer.launch();
const page = await browser.newPage();
const ctx = browser.defaultBrowserContext();
await ctx.overridePermissions('https://example.com', ['accelerometer']);
await ctx.clearPermissionOverrides();
});
// Geoloc
(async () => {
const browser = await puppeteer.launch();
const page = await browser.newPage();
page.setGeolocation({
accuracy: 10,
latitude: 0,
longitude: 0,
});
});
// Errors
(async () => {
const browser = await puppeteer.launch();
const page = await browser.newPage();
try {
await page.waitFor('test');
} catch (err) {
console.log(err instanceof TimeoutError);
}
});
// domcontentloaded page event test
(async () => {
const browser = await puppeteer.launch();
const page = await browser.newPage();
page.on('domcontentloaded', async () => {
page.evaluate(() => {
console.log('dom changed');
});
});
});
// evaluates return type of inner function
(async () => {
const browser = await puppeteer.launch();
const page = await browser.newPage();
const s = await page.evaluate(() => document.body.innerHTML);
console.log('body html has length', s.length);
});
// even through a double promise.
(async () => {
const browser = await puppeteer.launch();
const page = await browser.newPage();
const s = await page.evaluate(() => Promise.resolve(document.body.innerHTML));
console.log('body html has length', s.length);
});
// JSHandle.jsonValue produces compatible type
(async () => {
const browser = await puppeteer.launch();
const page = await browser.newPage();
const s = await page
.waitForFunction(
(searchStrs: string[]) => searchStrs.find(v => document.body.innerText.includes(v)),
{ timeout: 2000 },
['once', 'upon', 'a', 'midnight', 'dreary'])
.then(j => j.jsonValue());
console.log('found in page', s.toLowerCase());
});
// Element access
(async () => {
const browser = await puppeteer.launch();
const page = await browser.newPage();
const el = await page.$('input');
const val: string = await (await el!.getProperty('type')).jsonValue();
});
// Request manipualtion
(async () => {
const browser = await puppeteer.launch();
const page = await browser.newPage();
await page.setExtraHTTPHeaders({
a: '1'
});
});
// ElementHandles are well-typed
(async () => {
const browser = await puppeteer.launch();
const page = await browser.newPage();
const link: puppeteer.JSHandle = await page.evaluateHandle(
() => document.body.querySelector('a')
);
const linkEl: puppeteer.ElementHandle | null = link.asElement();
if (linkEl !== null) {
const href = await page.evaluate(
(el: HTMLElement): string | null => el.getAttribute('href'),
linkEl);
console.log('href is', href);
}
});
// test $$eval return type
(async () => {
const browser = await puppeteer.launch();
const page = await browser.newPage();
const paragraphContents: string[] = await page.$$eval(
'p', (ps: Element[]): string[] => ps.map(p => p.textContent || ''));
console.log('pgraph contents', paragraphContents);
});
// JSHandle of non-serializable works
(async () => {
const browser = await puppeteer.launch();
const page = await browser.newPage();
const reHandle: puppeteer.JSHandle = await page.evaluateHandle(
() => /\s*bananas?\s*/i,
);
const numMatchingEls: number = await page.$$eval(
'p', (els: Element[], re: RegExp) =>
els.filter(el => el.textContent && re.test(el.textContent)).length,
reHandle
);
console.log('there are', numMatchingEls, 'banana paragaphs');
});
(async () => {
const rev = '630727';
const defaultFetcher = puppeteer.createBrowserFetcher();
const options: puppeteer.FetcherOptions = {
host: 'https://storage.googleapis.com',
path: '/tmp/.local-chromium',
platform: 'linux',
};
const browserFetcher = puppeteer.createBrowserFetcher(options);
const canDownload = await browserFetcher.canDownload(rev);
if (canDownload) {
const revisionInfo = await browserFetcher.download(rev);
const localRevisions = await browserFetcher.localRevisions();
const browser = await puppeteer.launch({executablePath: revisionInfo.executablePath});
browser.close();
if (localRevisions.includes(rev)) {
await browserFetcher.remove(rev);
}
await browserFetcher.download(rev, (download, total) => {
console.log('downloadBytes:', download, 'totalBytes:', total);
});
await browserFetcher.remove(rev);
}
});
(async () => {
const browser = await puppeteer.launch();
const page = await browser.newPage();
const url = page.workers()[0].url();
if (page.target().type() === 'shared_worker') {
const a: number = await (await page.target().worker())!.evaluate(() => 1);
}
});
(async () => {
const browser = await puppeteer.launch();
const page = await browser.newPage();
const fileChooser = await page.waitForFileChooser({ timeout: 999 });
await fileChooser.cancel();
const isMultiple: boolean = fileChooser.isMultiple();
await fileChooser.accept(['/foo/bar']);
});