1 |
|
2 |
|
3 |
|
4 |
|
5 |
|
6 |
|
7 |
|
8 |
|
9 |
|
10 |
|
11 |
|
12 |
|
13 |
|
14 |
|
15 |
|
16 |
|
17 | const fs = require('fs');
|
18 | const EventEmitter = require('events');
|
19 | const mime = require('mime');
|
20 | const {NetworkManager} = require('./NetworkManager');
|
21 | const {Dialog} = require('./Dialog');
|
22 | const {EmulationManager} = require('./EmulationManager');
|
23 | const {FrameManager} = require('./FrameManager');
|
24 | const {Keyboard, Mouse, Touchscreen} = require('./Input');
|
25 | const Tracing = require('./Tracing');
|
26 | const {helper, debugError, assert} = require('./helper');
|
27 | const {Coverage} = require('./Coverage');
|
28 | const {Worker} = require('./Worker');
|
29 | const {createJSHandle} = require('./ExecutionContext');
|
30 |
|
31 | const writeFileAsync = helper.promisify(fs.writeFile);
|
32 |
|
33 | class Page extends EventEmitter {
|
34 | |
35 |
|
36 |
|
37 |
|
38 |
|
39 |
|
40 |
|
41 |
|
42 | static async create(client, target, ignoreHTTPSErrors, defaultViewport, screenshotTaskQueue) {
|
43 |
|
44 | await client.send('Page.enable');
|
45 | const {frameTree} = await client.send('Page.getFrameTree');
|
46 | const page = new Page(client, target, frameTree, ignoreHTTPSErrors, screenshotTaskQueue);
|
47 |
|
48 | await Promise.all([
|
49 | client.send('Target.setAutoAttach', {autoAttach: true, waitForDebuggerOnStart: false}),
|
50 | client.send('Page.setLifecycleEventsEnabled', { enabled: true }),
|
51 | client.send('Network.enable', {}),
|
52 | client.send('Runtime.enable', {}),
|
53 | client.send('Security.enable', {}),
|
54 | client.send('Performance.enable', {}),
|
55 | client.send('Log.enable', {}),
|
56 | ]);
|
57 | if (ignoreHTTPSErrors)
|
58 | await client.send('Security.setOverrideCertificateErrors', {override: true});
|
59 |
|
60 | if (defaultViewport)
|
61 | await page.setViewport(defaultViewport);
|
62 |
|
63 | return page;
|
64 | }
|
65 |
|
66 | |
67 |
|
68 |
|
69 |
|
70 |
|
71 |
|
72 |
|
73 | constructor(client, target, frameTree, ignoreHTTPSErrors, screenshotTaskQueue) {
|
74 | super();
|
75 | this._closed = false;
|
76 | this._client = client;
|
77 | this._target = target;
|
78 | this._keyboard = new Keyboard(client);
|
79 | this._mouse = new Mouse(client, this._keyboard);
|
80 | this._touchscreen = new Touchscreen(client, this._keyboard);
|
81 | this._networkManager = new NetworkManager(client);
|
82 |
|
83 | this._frameManager = new FrameManager(client, frameTree, this, this._networkManager);
|
84 | this._networkManager.setFrameManager(this._frameManager);
|
85 | this._emulationManager = new EmulationManager(client);
|
86 | this._tracing = new Tracing(client);
|
87 |
|
88 | this._pageBindings = new Map();
|
89 | this._ignoreHTTPSErrors = ignoreHTTPSErrors;
|
90 | this._coverage = new Coverage(client);
|
91 | this._javascriptEnabled = true;
|
92 |
|
93 | this._viewport = null;
|
94 |
|
95 | this._screenshotTaskQueue = screenshotTaskQueue;
|
96 |
|
97 |
|
98 | this._workers = new Map();
|
99 | client.on('Target.attachedToTarget', event => {
|
100 | if (event.targetInfo.type !== 'worker') {
|
101 |
|
102 | client.send('Target.detachFromTarget', {
|
103 | sessionId: event.sessionId
|
104 | }).catch(debugError);
|
105 | return;
|
106 | }
|
107 | const session = client._createSession(event.targetInfo.type, event.sessionId);
|
108 | const worker = new Worker(session, event.targetInfo.url, this._addConsoleMessage.bind(this), this._handleException.bind(this));
|
109 | this._workers.set(event.sessionId, worker);
|
110 | this.emit(Page.Events.WorkerCreated, worker);
|
111 |
|
112 | });
|
113 | client.on('Target.detachedFromTarget', event => {
|
114 | const worker = this._workers.get(event.sessionId);
|
115 | if (!worker)
|
116 | return;
|
117 | this.emit(Page.Events.WorkerDestroyed, worker);
|
118 | this._workers.delete(event.sessionId);
|
119 | });
|
120 |
|
121 | this._frameManager.on(FrameManager.Events.FrameAttached, event => this.emit(Page.Events.FrameAttached, event));
|
122 | this._frameManager.on(FrameManager.Events.FrameDetached, event => this.emit(Page.Events.FrameDetached, event));
|
123 | this._frameManager.on(FrameManager.Events.FrameNavigated, event => this.emit(Page.Events.FrameNavigated, event));
|
124 |
|
125 | this._networkManager.on(NetworkManager.Events.Request, event => this.emit(Page.Events.Request, event));
|
126 | this._networkManager.on(NetworkManager.Events.Response, event => this.emit(Page.Events.Response, event));
|
127 | this._networkManager.on(NetworkManager.Events.RequestFailed, event => this.emit(Page.Events.RequestFailed, event));
|
128 | this._networkManager.on(NetworkManager.Events.RequestFinished, event => this.emit(Page.Events.RequestFinished, event));
|
129 |
|
130 | client.on('Page.domContentEventFired', event => this.emit(Page.Events.DOMContentLoaded));
|
131 | client.on('Page.loadEventFired', event => this.emit(Page.Events.Load));
|
132 | client.on('Runtime.consoleAPICalled', event => this._onConsoleAPI(event));
|
133 | client.on('Runtime.bindingCalled', event => this._onBindingCalled(event));
|
134 | client.on('Page.javascriptDialogOpening', event => this._onDialog(event));
|
135 | client.on('Runtime.exceptionThrown', exception => this._handleException(exception.exceptionDetails));
|
136 | client.on('Security.certificateError', event => this._onCertificateError(event));
|
137 | client.on('Inspector.targetCrashed', event => this._onTargetCrashed());
|
138 | client.on('Performance.metrics', event => this._emitMetrics(event));
|
139 | client.on('Log.entryAdded', event => this._onLogEntryAdded(event));
|
140 | this._target._isClosedPromise.then(() => {
|
141 | this.emit(Page.Events.Close);
|
142 | this._closed = true;
|
143 | });
|
144 | }
|
145 |
|
146 | |
147 |
|
148 |
|
149 | async setGeolocation(options) {
|
150 | const { longitude, latitude, accuracy = 0} = options;
|
151 | if (longitude < -180 || longitude > 180)
|
152 | throw new Error(`Invalid longitude "${longitude}": precondition -180 <= LONGITUDE <= 180 failed.`);
|
153 | if (latitude < -90 || latitude > 90)
|
154 | throw new Error(`Invalid latitude "${latitude}": precondition -90 <= LATITUDE <= 90 failed.`);
|
155 | if (accuracy < 0)
|
156 | throw new Error(`Invalid accuracy "${accuracy}": precondition 0 <= ACCURACY failed.`);
|
157 | await this._client.send('Emulation.setGeolocationOverride', {longitude, latitude, accuracy});
|
158 | }
|
159 |
|
160 | |
161 |
|
162 |
|
163 | target() {
|
164 | return this._target;
|
165 | }
|
166 |
|
167 | |
168 |
|
169 |
|
170 | browser() {
|
171 | return this._target.browser();
|
172 | }
|
173 |
|
174 | _onTargetCrashed() {
|
175 | this.emit('error', new Error('Page crashed!'));
|
176 | }
|
177 |
|
178 | |
179 |
|
180 |
|
181 | _onLogEntryAdded(event) {
|
182 | const {level, text, args, source} = event.entry;
|
183 | if (args)
|
184 | args.map(arg => helper.releaseObject(this._client, arg));
|
185 | if (source !== 'worker')
|
186 | this.emit(Page.Events.Console, new ConsoleMessage(level, text));
|
187 | }
|
188 |
|
189 | |
190 |
|
191 |
|
192 | mainFrame() {
|
193 | return this._frameManager.mainFrame();
|
194 | }
|
195 |
|
196 | |
197 |
|
198 |
|
199 | get keyboard() {
|
200 | return this._keyboard;
|
201 | }
|
202 |
|
203 | |
204 |
|
205 |
|
206 | get touchscreen() {
|
207 | return this._touchscreen;
|
208 | }
|
209 |
|
210 | |
211 |
|
212 |
|
213 | get coverage() {
|
214 | return this._coverage;
|
215 | }
|
216 |
|
217 | |
218 |
|
219 |
|
220 | get tracing() {
|
221 | return this._tracing;
|
222 | }
|
223 |
|
224 | |
225 |
|
226 |
|
227 | frames() {
|
228 | return this._frameManager.frames();
|
229 | }
|
230 |
|
231 | |
232 |
|
233 |
|
234 | workers() {
|
235 | return Array.from(this._workers.values());
|
236 | }
|
237 |
|
238 | |
239 |
|
240 |
|
241 | async setRequestInterception(value) {
|
242 | return this._networkManager.setRequestInterception(value);
|
243 | }
|
244 |
|
245 | |
246 |
|
247 |
|
248 | setOfflineMode(enabled) {
|
249 | return this._networkManager.setOfflineMode(enabled);
|
250 | }
|
251 |
|
252 | |
253 |
|
254 |
|
255 | setDefaultNavigationTimeout(timeout) {
|
256 | this._frameManager.setDefaultNavigationTimeout(timeout);
|
257 | }
|
258 |
|
259 | |
260 |
|
261 |
|
262 | _onCertificateError(event) {
|
263 | if (!this._ignoreHTTPSErrors)
|
264 | return;
|
265 | this._client.send('Security.handleCertificateError', {
|
266 | eventId: event.eventId,
|
267 | action: 'continue'
|
268 | }).catch(debugError);
|
269 | }
|
270 |
|
271 | |
272 |
|
273 |
|
274 |
|
275 | async $(selector) {
|
276 | return this.mainFrame().$(selector);
|
277 | }
|
278 |
|
279 | |
280 |
|
281 |
|
282 |
|
283 |
|
284 | async evaluateHandle(pageFunction, ...args) {
|
285 | const context = await this.mainFrame().executionContext();
|
286 | return context.evaluateHandle(pageFunction, ...args);
|
287 | }
|
288 |
|
289 | |
290 |
|
291 |
|
292 |
|
293 | async queryObjects(prototypeHandle) {
|
294 | const context = await this.mainFrame().executionContext();
|
295 | return context.queryObjects(prototypeHandle);
|
296 | }
|
297 |
|
298 | |
299 |
|
300 |
|
301 |
|
302 |
|
303 |
|
304 | async $eval(selector, pageFunction, ...args) {
|
305 | return this.mainFrame().$eval(selector, pageFunction, ...args);
|
306 | }
|
307 |
|
308 | |
309 |
|
310 |
|
311 |
|
312 |
|
313 |
|
314 | async $$eval(selector, pageFunction, ...args) {
|
315 | return this.mainFrame().$$eval(selector, pageFunction, ...args);
|
316 | }
|
317 |
|
318 | |
319 |
|
320 |
|
321 |
|
322 | async $$(selector) {
|
323 | return this.mainFrame().$$(selector);
|
324 | }
|
325 |
|
326 | |
327 |
|
328 |
|
329 |
|
330 | async $x(expression) {
|
331 | return this.mainFrame().$x(expression);
|
332 | }
|
333 |
|
334 | |
335 |
|
336 |
|
337 |
|
338 | async cookies(...urls) {
|
339 | return (await this._client.send('Network.getCookies', {
|
340 | urls: urls.length ? urls : [this.url()]
|
341 | })).cookies;
|
342 | }
|
343 |
|
344 | |
345 |
|
346 |
|
347 | async deleteCookie(...cookies) {
|
348 | const pageURL = this.url();
|
349 | for (const cookie of cookies) {
|
350 | const item = Object.assign({}, cookie);
|
351 | if (!cookie.url && pageURL.startsWith('http'))
|
352 | item.url = pageURL;
|
353 | await this._client.send('Network.deleteCookies', item);
|
354 | }
|
355 | }
|
356 |
|
357 | |
358 |
|
359 |
|
360 | async setCookie(...cookies) {
|
361 | const pageURL = this.url();
|
362 | const startsWithHTTP = pageURL.startsWith('http');
|
363 | const items = cookies.map(cookie => {
|
364 | const item = Object.assign({}, cookie);
|
365 | if (!item.url && startsWithHTTP)
|
366 | item.url = pageURL;
|
367 | assert(
|
368 | item.url !== 'about:blank',
|
369 | `Blank page can not have cookie "${item.name}"`
|
370 | );
|
371 | assert(
|
372 | !String.prototype.startsWith.call(item.url || '', 'data:'),
|
373 | `Data URL page can not have cookie "${item.name}"`
|
374 | );
|
375 | return item;
|
376 | });
|
377 | await this.deleteCookie(...items);
|
378 | if (items.length)
|
379 | await this._client.send('Network.setCookies', { cookies: items });
|
380 | }
|
381 |
|
382 | |
383 |
|
384 |
|
385 |
|
386 | async addScriptTag(options) {
|
387 | return this.mainFrame().addScriptTag(options);
|
388 | }
|
389 |
|
390 | |
391 |
|
392 |
|
393 |
|
394 | async addStyleTag(options) {
|
395 | return this.mainFrame().addStyleTag(options);
|
396 | }
|
397 |
|
398 | |
399 |
|
400 |
|
401 |
|
402 | async exposeFunction(name, puppeteerFunction) {
|
403 | if (this._pageBindings.has(name))
|
404 | throw new Error(`Failed to add page binding with name ${name}: window['${name}'] already exists!`);
|
405 | this._pageBindings.set(name, puppeteerFunction);
|
406 |
|
407 | const expression = helper.evaluationString(addPageBinding, name);
|
408 | await this._client.send('Runtime.addBinding', {name: name});
|
409 | await this._client.send('Page.addScriptToEvaluateOnNewDocument', {source: expression});
|
410 | await Promise.all(this.frames().map(frame => frame.evaluate(expression).catch(debugError)));
|
411 |
|
412 | function addPageBinding(bindingName) {
|
413 | const binding = window[bindingName];
|
414 | window[bindingName] = async(...args) => {
|
415 | const me = window[bindingName];
|
416 | let callbacks = me['callbacks'];
|
417 | if (!callbacks) {
|
418 | callbacks = new Map();
|
419 | me['callbacks'] = callbacks;
|
420 | }
|
421 | const seq = (me['lastSeq'] || 0) + 1;
|
422 | me['lastSeq'] = seq;
|
423 | const promise = new Promise(fulfill => callbacks.set(seq, fulfill));
|
424 | binding(JSON.stringify({name: bindingName, seq, args}));
|
425 | return promise;
|
426 | };
|
427 | }
|
428 | }
|
429 |
|
430 | |
431 |
|
432 |
|
433 | async authenticate(credentials) {
|
434 | return this._networkManager.authenticate(credentials);
|
435 | }
|
436 |
|
437 | |
438 |
|
439 |
|
440 | async setExtraHTTPHeaders(headers) {
|
441 | return this._networkManager.setExtraHTTPHeaders(headers);
|
442 | }
|
443 |
|
444 | |
445 |
|
446 |
|
447 | async setUserAgent(userAgent) {
|
448 | return this._networkManager.setUserAgent(userAgent);
|
449 | }
|
450 |
|
451 | |
452 |
|
453 |
|
454 | async metrics() {
|
455 | const response = await this._client.send('Performance.getMetrics');
|
456 | return this._buildMetricsObject(response.metrics);
|
457 | }
|
458 |
|
459 | |
460 |
|
461 |
|
462 | _emitMetrics(event) {
|
463 | this.emit(Page.Events.Metrics, {
|
464 | title: event.title,
|
465 | metrics: this._buildMetricsObject(event.metrics)
|
466 | });
|
467 | }
|
468 |
|
469 | |
470 |
|
471 |
|
472 |
|
473 | _buildMetricsObject(metrics) {
|
474 | const result = {};
|
475 | for (const metric of metrics || []) {
|
476 | if (supportedMetrics.has(metric.name))
|
477 | result[metric.name] = metric.value;
|
478 | }
|
479 | return result;
|
480 | }
|
481 |
|
482 | |
483 |
|
484 |
|
485 | _handleException(exceptionDetails) {
|
486 | const message = helper.getExceptionMessage(exceptionDetails);
|
487 | const err = new Error(message);
|
488 | err.stack = '';
|
489 | this.emit(Page.Events.PageError, err);
|
490 | }
|
491 |
|
492 | |
493 |
|
494 |
|
495 | async _onConsoleAPI(event) {
|
496 | const context = this._frameManager.executionContextById(event.executionContextId);
|
497 | const values = event.args.map(arg => createJSHandle(context, arg));
|
498 | this._addConsoleMessage(event.type, values);
|
499 | }
|
500 |
|
501 | |
502 |
|
503 |
|
504 | async _onBindingCalled(event) {
|
505 | const {name, seq, args} = JSON.parse(event.payload);
|
506 | const result = await this._pageBindings.get(name)(...args);
|
507 | const expression = helper.evaluationString(deliverResult, name, seq, result);
|
508 | this._client.send('Runtime.evaluate', { expression, contextId: event.executionContextId }).catch(debugError);
|
509 |
|
510 | function deliverResult(name, seq, result) {
|
511 | window[name]['callbacks'].get(seq)(result);
|
512 | window[name]['callbacks'].delete(seq);
|
513 | }
|
514 | }
|
515 |
|
516 | |
517 |
|
518 |
|
519 |
|
520 | _addConsoleMessage(type, args) {
|
521 | if (!this.listenerCount(Page.Events.Console)) {
|
522 | args.forEach(arg => arg.dispose());
|
523 | return;
|
524 | }
|
525 | const textTokens = [];
|
526 | for (const arg of args) {
|
527 | const remoteObject = arg._remoteObject;
|
528 | if (remoteObject.objectId)
|
529 | textTokens.push(arg.toString());
|
530 | else
|
531 | textTokens.push(helper.valueFromRemoteObject(remoteObject));
|
532 | }
|
533 | const message = new ConsoleMessage(type, textTokens.join(' '), args);
|
534 | this.emit(Page.Events.Console, message);
|
535 | }
|
536 |
|
537 | _onDialog(event) {
|
538 | let dialogType = null;
|
539 | if (event.type === 'alert')
|
540 | dialogType = Dialog.Type.Alert;
|
541 | else if (event.type === 'confirm')
|
542 | dialogType = Dialog.Type.Confirm;
|
543 | else if (event.type === 'prompt')
|
544 | dialogType = Dialog.Type.Prompt;
|
545 | else if (event.type === 'beforeunload')
|
546 | dialogType = Dialog.Type.BeforeUnload;
|
547 | assert(dialogType, 'Unknown javascript dialog type: ' + event.type);
|
548 | const dialog = new Dialog(this._client, dialogType, event.message, event.defaultPrompt);
|
549 | this.emit(Page.Events.Dialog, dialog);
|
550 | }
|
551 |
|
552 | |
553 |
|
554 |
|
555 | url() {
|
556 | return this.mainFrame().url();
|
557 | }
|
558 |
|
559 | |
560 |
|
561 |
|
562 | async content() {
|
563 | return await this._frameManager.mainFrame().content();
|
564 | }
|
565 |
|
566 | |
567 |
|
568 |
|
569 | async setContent(html) {
|
570 | await this._frameManager.mainFrame().setContent(html);
|
571 | }
|
572 |
|
573 | |
574 |
|
575 |
|
576 |
|
577 |
|
578 | async goto(url, options = {}) {
|
579 | return await this._frameManager.mainFrame().goto(url, options);
|
580 | }
|
581 |
|
582 | |
583 |
|
584 |
|
585 |
|
586 | async reload(options) {
|
587 | const [response] = await Promise.all([
|
588 | this.waitForNavigation(options),
|
589 | this._client.send('Page.reload')
|
590 | ]);
|
591 | return response;
|
592 | }
|
593 |
|
594 | |
595 |
|
596 |
|
597 |
|
598 | async waitForNavigation(options = {}) {
|
599 | return await this._frameManager.mainFrame().waitForNavigation(options);
|
600 | }
|
601 |
|
602 | |
603 |
|
604 |
|
605 |
|
606 |
|
607 | async waitForRequest(urlOrPredicate, options = {}) {
|
608 | const timeout = typeof options.timeout === 'number' ? options.timeout : 30000;
|
609 | return helper.waitForEvent(this._networkManager, NetworkManager.Events.Request, request => {
|
610 | if (helper.isString(urlOrPredicate))
|
611 | return (urlOrPredicate === request.url());
|
612 | if (typeof urlOrPredicate === 'function')
|
613 | return !!(urlOrPredicate(request));
|
614 | return false;
|
615 | }, timeout);
|
616 | }
|
617 |
|
618 | |
619 |
|
620 |
|
621 |
|
622 |
|
623 | async waitForResponse(urlOrPredicate, options = {}) {
|
624 | const timeout = typeof options.timeout === 'number' ? options.timeout : 30000;
|
625 | return helper.waitForEvent(this._networkManager, NetworkManager.Events.Response, response => {
|
626 | if (helper.isString(urlOrPredicate))
|
627 | return (urlOrPredicate === response.url());
|
628 | if (typeof urlOrPredicate === 'function')
|
629 | return !!(urlOrPredicate(response));
|
630 | return false;
|
631 | }, timeout);
|
632 | }
|
633 |
|
634 | |
635 |
|
636 |
|
637 |
|
638 | async goBack(options) {
|
639 | return this._go(-1, options);
|
640 | }
|
641 |
|
642 | |
643 |
|
644 |
|
645 |
|
646 | async goForward(options) {
|
647 | return this._go(+1, options);
|
648 | }
|
649 |
|
650 | |
651 |
|
652 |
|
653 |
|
654 | async _go(delta, options) {
|
655 | const history = await this._client.send('Page.getNavigationHistory');
|
656 | const entry = history.entries[history.currentIndex + delta];
|
657 | if (!entry)
|
658 | return null;
|
659 | const [response] = await Promise.all([
|
660 | this.waitForNavigation(options),
|
661 | this._client.send('Page.navigateToHistoryEntry', {entryId: entry.id}),
|
662 | ]);
|
663 | return response;
|
664 | }
|
665 |
|
666 | async bringToFront() {
|
667 | await this._client.send('Page.bringToFront');
|
668 | }
|
669 |
|
670 | |
671 |
|
672 |
|
673 | async emulate(options) {
|
674 | return Promise.all([
|
675 | this.setViewport(options.viewport),
|
676 | this.setUserAgent(options.userAgent)
|
677 | ]);
|
678 | }
|
679 |
|
680 | |
681 |
|
682 |
|
683 | async setJavaScriptEnabled(enabled) {
|
684 | if (this._javascriptEnabled === enabled)
|
685 | return;
|
686 | this._javascriptEnabled = enabled;
|
687 | await this._client.send('Emulation.setScriptExecutionDisabled', { value: !enabled });
|
688 | }
|
689 |
|
690 | |
691 |
|
692 |
|
693 | async setBypassCSP(enabled) {
|
694 | await this._client.send('Page.setBypassCSP', { enabled });
|
695 | }
|
696 |
|
697 | |
698 |
|
699 |
|
700 | async emulateMedia(mediaType) {
|
701 | assert(mediaType === 'screen' || mediaType === 'print' || mediaType === null, 'Unsupported media type: ' + mediaType);
|
702 | await this._client.send('Emulation.setEmulatedMedia', {media: mediaType || ''});
|
703 | }
|
704 |
|
705 | |
706 |
|
707 |
|
708 | async setViewport(viewport) {
|
709 | const needsReload = await this._emulationManager.emulateViewport(viewport);
|
710 | this._viewport = viewport;
|
711 | if (needsReload)
|
712 | await this.reload();
|
713 | }
|
714 |
|
715 | |
716 |
|
717 |
|
718 | viewport() {
|
719 | return this._viewport;
|
720 | }
|
721 |
|
722 | |
723 |
|
724 |
|
725 |
|
726 |
|
727 | async evaluate(pageFunction, ...args) {
|
728 | return this._frameManager.mainFrame().evaluate(pageFunction, ...args);
|
729 | }
|
730 |
|
731 | |
732 |
|
733 |
|
734 |
|
735 | async evaluateOnNewDocument(pageFunction, ...args) {
|
736 | const source = helper.evaluationString(pageFunction, ...args);
|
737 | await this._client.send('Page.addScriptToEvaluateOnNewDocument', { source });
|
738 | }
|
739 |
|
740 | |
741 |
|
742 |
|
743 |
|
744 | async setCacheEnabled(enabled = true) {
|
745 | await this._client.send('Network.setCacheDisabled', {cacheDisabled: !enabled});
|
746 | }
|
747 |
|
748 | |
749 |
|
750 |
|
751 |
|
752 | async screenshot(options = {}) {
|
753 | let screenshotType = null;
|
754 |
|
755 |
|
756 | if (options.type) {
|
757 | assert(options.type === 'png' || options.type === 'jpeg', 'Unknown options.type value: ' + options.type);
|
758 | screenshotType = options.type;
|
759 | } else if (options.path) {
|
760 | const mimeType = mime.getType(options.path);
|
761 | if (mimeType === 'image/png')
|
762 | screenshotType = 'png';
|
763 | else if (mimeType === 'image/jpeg')
|
764 | screenshotType = 'jpeg';
|
765 | assert(screenshotType, 'Unsupported screenshot mime type: ' + mimeType);
|
766 | }
|
767 |
|
768 | if (!screenshotType)
|
769 | screenshotType = 'png';
|
770 |
|
771 | if (options.quality) {
|
772 | assert(screenshotType === 'jpeg', 'options.quality is unsupported for the ' + screenshotType + ' screenshots');
|
773 | assert(typeof options.quality === 'number', 'Expected options.quality to be a number but found ' + (typeof options.quality));
|
774 | assert(Number.isInteger(options.quality), 'Expected options.quality to be an integer');
|
775 | assert(options.quality >= 0 && options.quality <= 100, 'Expected options.quality to be between 0 and 100 (inclusive), got ' + options.quality);
|
776 | }
|
777 | assert(!options.clip || !options.fullPage, 'options.clip and options.fullPage are exclusive');
|
778 | if (options.clip) {
|
779 | assert(typeof options.clip.x === 'number', 'Expected options.clip.x to be a number but found ' + (typeof options.clip.x));
|
780 | assert(typeof options.clip.y === 'number', 'Expected options.clip.y to be a number but found ' + (typeof options.clip.y));
|
781 | assert(typeof options.clip.width === 'number', 'Expected options.clip.width to be a number but found ' + (typeof options.clip.width));
|
782 | assert(typeof options.clip.height === 'number', 'Expected options.clip.height to be a number but found ' + (typeof options.clip.height));
|
783 | }
|
784 | return this._screenshotTaskQueue.postTask(this._screenshotTask.bind(this, screenshotType, options));
|
785 | }
|
786 |
|
787 | |
788 |
|
789 |
|
790 |
|
791 |
|
792 | async _screenshotTask(format, options) {
|
793 | await this._client.send('Target.activateTarget', {targetId: this._target._targetId});
|
794 | let clip = options.clip ? Object.assign({}, options['clip']) : undefined;
|
795 | if (clip)
|
796 | clip.scale = 1;
|
797 |
|
798 | if (options.fullPage) {
|
799 | assert(this._viewport, 'fullPage screenshots do not work without first setting viewport.');
|
800 | const metrics = await this._client.send('Page.getLayoutMetrics');
|
801 | const width = Math.ceil(metrics.contentSize.width);
|
802 | const height = Math.ceil(metrics.contentSize.height);
|
803 |
|
804 |
|
805 | clip = { x: 0, y: 0, width, height, scale: 1 };
|
806 | const mobile = this._viewport.isMobile || false;
|
807 | const deviceScaleFactor = this._viewport.deviceScaleFactor || 1;
|
808 | const landscape = this._viewport.isLandscape || false;
|
809 |
|
810 | const screenOrientation = landscape ? { angle: 90, type: 'landscapePrimary' } : { angle: 0, type: 'portraitPrimary' };
|
811 | await this._client.send('Emulation.setDeviceMetricsOverride', { mobile, width, height, deviceScaleFactor, screenOrientation });
|
812 | }
|
813 | const shouldSetDefaultBackground = options.omitBackground && format === 'png';
|
814 | if (shouldSetDefaultBackground)
|
815 | await this._client.send('Emulation.setDefaultBackgroundColorOverride', { color: { r: 0, g: 0, b: 0, a: 0 } });
|
816 | const result = await this._client.send('Page.captureScreenshot', { format, quality: options.quality, clip });
|
817 | if (shouldSetDefaultBackground)
|
818 | await this._client.send('Emulation.setDefaultBackgroundColorOverride');
|
819 |
|
820 | if (options.fullPage)
|
821 | await this.setViewport(this._viewport);
|
822 |
|
823 | const buffer = options.encoding === 'base64' ? result.data : Buffer.from(result.data, 'base64');
|
824 | if (options.path)
|
825 | await writeFileAsync(options.path, buffer);
|
826 | return buffer;
|
827 | }
|
828 |
|
829 | |
830 |
|
831 |
|
832 |
|
833 | async pdf(options = {}) {
|
834 | const scale = options.scale || 1;
|
835 | const displayHeaderFooter = !!options.displayHeaderFooter;
|
836 | const headerTemplate = options.headerTemplate || '';
|
837 | const footerTemplate = options.footerTemplate || '';
|
838 | const printBackground = !!options.printBackground;
|
839 | const landscape = !!options.landscape;
|
840 | const pageRanges = options.pageRanges || '';
|
841 |
|
842 | let paperWidth = 8.5;
|
843 | let paperHeight = 11;
|
844 | if (options.format) {
|
845 | const format = Page.PaperFormats[options.format.toLowerCase()];
|
846 | assert(format, 'Unknown paper format: ' + options.format);
|
847 | paperWidth = format.width;
|
848 | paperHeight = format.height;
|
849 | } else {
|
850 | paperWidth = convertPrintParameterToInches(options.width) || paperWidth;
|
851 | paperHeight = convertPrintParameterToInches(options.height) || paperHeight;
|
852 | }
|
853 |
|
854 | const marginOptions = options.margin || {};
|
855 | const marginTop = convertPrintParameterToInches(marginOptions.top) || 0;
|
856 | const marginLeft = convertPrintParameterToInches(marginOptions.left) || 0;
|
857 | const marginBottom = convertPrintParameterToInches(marginOptions.bottom) || 0;
|
858 | const marginRight = convertPrintParameterToInches(marginOptions.right) || 0;
|
859 | const preferCSSPageSize = options.preferCSSPageSize || false;
|
860 |
|
861 | const result = await this._client.send('Page.printToPDF', {
|
862 | landscape: landscape,
|
863 | displayHeaderFooter: displayHeaderFooter,
|
864 | headerTemplate: headerTemplate,
|
865 | footerTemplate: footerTemplate,
|
866 | printBackground: printBackground,
|
867 | scale: scale,
|
868 | paperWidth: paperWidth,
|
869 | paperHeight: paperHeight,
|
870 | marginTop: marginTop,
|
871 | marginBottom: marginBottom,
|
872 | marginLeft: marginLeft,
|
873 | marginRight: marginRight,
|
874 | pageRanges: pageRanges,
|
875 | preferCSSPageSize: preferCSSPageSize
|
876 | });
|
877 | const buffer = Buffer.from(result.data, 'base64');
|
878 | if (options.path)
|
879 | await writeFileAsync(options.path, buffer);
|
880 | return buffer;
|
881 | }
|
882 |
|
883 | |
884 |
|
885 |
|
886 | async title() {
|
887 | return this.mainFrame().title();
|
888 | }
|
889 |
|
890 | |
891 |
|
892 |
|
893 | async close(options = {runBeforeUnload: undefined}) {
|
894 | assert(!!this._client._connection, 'Protocol error: Connection closed. Most likely the page has been closed.');
|
895 | const runBeforeUnload = !!options.runBeforeUnload;
|
896 | if (runBeforeUnload) {
|
897 | await this._client.send('Page.close');
|
898 | } else {
|
899 | await this._client._connection.send('Target.closeTarget', { targetId: this._target._targetId });
|
900 | await this._target._isClosedPromise;
|
901 | }
|
902 | }
|
903 |
|
904 | |
905 |
|
906 |
|
907 | isClosed() {
|
908 | return this._closed;
|
909 | }
|
910 |
|
911 | |
912 |
|
913 |
|
914 | get mouse() {
|
915 | return this._mouse;
|
916 | }
|
917 |
|
918 | |
919 |
|
920 |
|
921 |
|
922 | click(selector, options = {}) {
|
923 | return this.mainFrame().click(selector, options);
|
924 | }
|
925 |
|
926 | |
927 |
|
928 |
|
929 | focus(selector) {
|
930 | return this.mainFrame().focus(selector);
|
931 | }
|
932 |
|
933 | |
934 |
|
935 |
|
936 | hover(selector) {
|
937 | return this.mainFrame().hover(selector);
|
938 | }
|
939 |
|
940 | |
941 |
|
942 |
|
943 |
|
944 |
|
945 | select(selector, ...values) {
|
946 | return this.mainFrame().select(selector, ...values);
|
947 | }
|
948 |
|
949 | |
950 |
|
951 |
|
952 | tap(selector) {
|
953 | return this.mainFrame().tap(selector);
|
954 | }
|
955 |
|
956 | |
957 |
|
958 |
|
959 |
|
960 |
|
961 | type(selector, text, options) {
|
962 | return this.mainFrame().type(selector, text, options);
|
963 | }
|
964 |
|
965 | |
966 |
|
967 |
|
968 |
|
969 |
|
970 |
|
971 | waitFor(selectorOrFunctionOrTimeout, options = {}, ...args) {
|
972 | return this.mainFrame().waitFor(selectorOrFunctionOrTimeout, options, ...args);
|
973 | }
|
974 |
|
975 | |
976 |
|
977 |
|
978 |
|
979 |
|
980 | waitForSelector(selector, options = {}) {
|
981 | return this.mainFrame().waitForSelector(selector, options);
|
982 | }
|
983 |
|
984 | |
985 |
|
986 |
|
987 |
|
988 |
|
989 | waitForXPath(xpath, options = {}) {
|
990 | return this.mainFrame().waitForXPath(xpath, options);
|
991 | }
|
992 |
|
993 | |
994 |
|
995 |
|
996 |
|
997 |
|
998 |
|
999 | waitForFunction(pageFunction, options = {}, ...args) {
|
1000 | return this.mainFrame().waitForFunction(pageFunction, options, ...args);
|
1001 | }
|
1002 | }
|
1003 |
|
1004 |
|
1005 | const supportedMetrics = new Set([
|
1006 | 'Timestamp',
|
1007 | 'Documents',
|
1008 | 'Frames',
|
1009 | 'JSEventListeners',
|
1010 | 'Nodes',
|
1011 | 'LayoutCount',
|
1012 | 'RecalcStyleCount',
|
1013 | 'LayoutDuration',
|
1014 | 'RecalcStyleDuration',
|
1015 | 'ScriptDuration',
|
1016 | 'TaskDuration',
|
1017 | 'JSHeapUsedSize',
|
1018 | 'JSHeapTotalSize',
|
1019 | ]);
|
1020 |
|
1021 |
|
1022 | Page.PaperFormats = {
|
1023 | letter: {width: 8.5, height: 11},
|
1024 | legal: {width: 8.5, height: 14},
|
1025 | tabloid: {width: 11, height: 17},
|
1026 | ledger: {width: 17, height: 11},
|
1027 | a0: {width: 33.1, height: 46.8 },
|
1028 | a1: {width: 23.4, height: 33.1 },
|
1029 | a2: {width: 16.5, height: 23.4 },
|
1030 | a3: {width: 11.7, height: 16.5 },
|
1031 | a4: {width: 8.27, height: 11.7 },
|
1032 | a5: {width: 5.83, height: 8.27 },
|
1033 | a6: {width: 4.13, height: 5.83 },
|
1034 | };
|
1035 |
|
1036 | const unitToPixels = {
|
1037 | 'px': 1,
|
1038 | 'in': 96,
|
1039 | 'cm': 37.8,
|
1040 | 'mm': 3.78
|
1041 | };
|
1042 |
|
1043 |
|
1044 |
|
1045 |
|
1046 |
|
1047 | function convertPrintParameterToInches(parameter) {
|
1048 | if (typeof parameter === 'undefined')
|
1049 | return undefined;
|
1050 | let pixels;
|
1051 | if (helper.isNumber(parameter)) {
|
1052 |
|
1053 | pixels = (parameter);
|
1054 | } else if (helper.isString(parameter)) {
|
1055 | const text = (parameter);
|
1056 | let unit = text.substring(text.length - 2).toLowerCase();
|
1057 | let valueText = '';
|
1058 | if (unitToPixels.hasOwnProperty(unit)) {
|
1059 | valueText = text.substring(0, text.length - 2);
|
1060 | } else {
|
1061 |
|
1062 |
|
1063 | unit = 'px';
|
1064 | valueText = text;
|
1065 | }
|
1066 | const value = Number(valueText);
|
1067 | assert(!isNaN(value), 'Failed to parse parameter value: ' + text);
|
1068 | pixels = value * unitToPixels[unit];
|
1069 | } else {
|
1070 | throw new Error('page.pdf() Cannot handle parameter type: ' + (typeof parameter));
|
1071 | }
|
1072 | return pixels / 96;
|
1073 | }
|
1074 |
|
1075 | Page.Events = {
|
1076 | Close: 'close',
|
1077 | Console: 'console',
|
1078 | Dialog: 'dialog',
|
1079 | DOMContentLoaded: 'domcontentloaded',
|
1080 | Error: 'error',
|
1081 |
|
1082 |
|
1083 | PageError: 'pageerror',
|
1084 | Request: 'request',
|
1085 | Response: 'response',
|
1086 | RequestFailed: 'requestfailed',
|
1087 | RequestFinished: 'requestfinished',
|
1088 | FrameAttached: 'frameattached',
|
1089 | FrameDetached: 'framedetached',
|
1090 | FrameNavigated: 'framenavigated',
|
1091 | Load: 'load',
|
1092 | Metrics: 'metrics',
|
1093 | WorkerCreated: 'workercreated',
|
1094 | WorkerDestroyed: 'workerdestroyed',
|
1095 | };
|
1096 |
|
1097 |
|
1098 |
|
1099 |
|
1100 |
|
1101 |
|
1102 |
|
1103 |
|
1104 |
|
1105 |
|
1106 |
|
1107 |
|
1108 |
|
1109 |
|
1110 |
|
1111 |
|
1112 |
|
1113 |
|
1114 |
|
1115 |
|
1116 |
|
1117 |
|
1118 |
|
1119 |
|
1120 |
|
1121 |
|
1122 |
|
1123 |
|
1124 |
|
1125 |
|
1126 | class ConsoleMessage {
|
1127 | |
1128 |
|
1129 |
|
1130 |
|
1131 |
|
1132 | constructor(type, text, args = []) {
|
1133 | this._type = type;
|
1134 | this._text = text;
|
1135 | this._args = args;
|
1136 | }
|
1137 |
|
1138 | |
1139 |
|
1140 |
|
1141 | type() {
|
1142 | return this._type;
|
1143 | }
|
1144 |
|
1145 | |
1146 |
|
1147 |
|
1148 | text() {
|
1149 | return this._text;
|
1150 | }
|
1151 |
|
1152 | |
1153 |
|
1154 |
|
1155 | args() {
|
1156 | return this._args;
|
1157 | }
|
1158 | }
|
1159 |
|
1160 |
|
1161 | module.exports = {Page};
|
1162 | helper.tracePublicAPI(Page);
|