UNPKG

35.3 kBJavaScriptView Raw
1/**
2 * Copyright 2017 Google Inc. All rights reserved.
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17const fs = require('fs');
18const EventEmitter = require('events');
19const mime = require('mime');
20const {NetworkManager} = require('./NetworkManager');
21const {Dialog} = require('./Dialog');
22const {EmulationManager} = require('./EmulationManager');
23const {FrameManager} = require('./FrameManager');
24const {Keyboard, Mouse, Touchscreen} = require('./Input');
25const Tracing = require('./Tracing');
26const {helper, debugError, assert} = require('./helper');
27const {Coverage} = require('./Coverage');
28const {Worker} = require('./Worker');
29const {createJSHandle} = require('./ExecutionContext');
30
31const writeFileAsync = helper.promisify(fs.writeFile);
32
33class Page extends EventEmitter {
34 /**
35 * @param {!Puppeteer.CDPSession} client
36 * @param {!Puppeteer.Target} target
37 * @param {boolean} ignoreHTTPSErrors
38 * @param {?Puppeteer.Viewport} defaultViewport
39 * @param {!Puppeteer.TaskQueue} screenshotTaskQueue
40 * @return {!Promise<!Page>}
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 // Initialize default page size.
60 if (defaultViewport)
61 await page.setViewport(defaultViewport);
62
63 return page;
64 }
65
66 /**
67 * @param {!Puppeteer.CDPSession} client
68 * @param {!Puppeteer.Target} target
69 * @param {!Protocol.Page.FrameTree} frameTree
70 * @param {boolean} ignoreHTTPSErrors
71 * @param {!Puppeteer.TaskQueue} screenshotTaskQueue
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 /** @type {!FrameManager} */
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 /** @type {!Map<string, Function>} */
88 this._pageBindings = new Map();
89 this._ignoreHTTPSErrors = ignoreHTTPSErrors;
90 this._coverage = new Coverage(client);
91 this._javascriptEnabled = true;
92 /** @type {?Puppeteer.Viewport} */
93 this._viewport = null;
94
95 this._screenshotTaskQueue = screenshotTaskQueue;
96
97 /** @type {!Map<string, Worker>} */
98 this._workers = new Map();
99 client.on('Target.attachedToTarget', event => {
100 if (event.targetInfo.type !== 'worker') {
101 // If we don't detach from service workers, they will never die.
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 * @param {!{longitude: number, latitude: number, accuracy: (number|undefined)}} options
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 * @return {!Puppeteer.Target}
162 */
163 target() {
164 return this._target;
165 }
166
167 /**
168 * @return {!Puppeteer.Browser}
169 */
170 browser() {
171 return this._target.browser();
172 }
173
174 _onTargetCrashed() {
175 this.emit('error', new Error('Page crashed!'));
176 }
177
178 /**
179 * @param {!Protocol.Log.entryAddedPayload} event
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 * @return {!Puppeteer.Frame}
191 */
192 mainFrame() {
193 return this._frameManager.mainFrame();
194 }
195
196 /**
197 * @return {!Keyboard}
198 */
199 get keyboard() {
200 return this._keyboard;
201 }
202
203 /**
204 * @return {!Touchscreen}
205 */
206 get touchscreen() {
207 return this._touchscreen;
208 }
209
210 /**
211 * @return {!Coverage}
212 */
213 get coverage() {
214 return this._coverage;
215 }
216
217 /**
218 * @return {!Tracing}
219 */
220 get tracing() {
221 return this._tracing;
222 }
223
224 /**
225 * @return {!Array<Puppeteer.Frame>}
226 */
227 frames() {
228 return this._frameManager.frames();
229 }
230
231 /**
232 * @return {!Array<!Worker>}
233 */
234 workers() {
235 return Array.from(this._workers.values());
236 }
237
238 /**
239 * @param {boolean} value
240 */
241 async setRequestInterception(value) {
242 return this._networkManager.setRequestInterception(value);
243 }
244
245 /**
246 * @param {boolean} enabled
247 */
248 setOfflineMode(enabled) {
249 return this._networkManager.setOfflineMode(enabled);
250 }
251
252 /**
253 * @param {number} timeout
254 */
255 setDefaultNavigationTimeout(timeout) {
256 this._frameManager.setDefaultNavigationTimeout(timeout);
257 }
258
259 /**
260 * @param {!Protocol.Security.certificateErrorPayload} event
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 * @param {string} selector
273 * @return {!Promise<?Puppeteer.ElementHandle>}
274 */
275 async $(selector) {
276 return this.mainFrame().$(selector);
277 }
278
279 /**
280 * @param {function()|string} pageFunction
281 * @param {!Array<*>} args
282 * @return {!Promise<!Puppeteer.JSHandle>}
283 */
284 async evaluateHandle(pageFunction, ...args) {
285 const context = await this.mainFrame().executionContext();
286 return context.evaluateHandle(pageFunction, ...args);
287 }
288
289 /**
290 * @param {!Puppeteer.JSHandle} prototypeHandle
291 * @return {!Promise<!Puppeteer.JSHandle>}
292 */
293 async queryObjects(prototypeHandle) {
294 const context = await this.mainFrame().executionContext();
295 return context.queryObjects(prototypeHandle);
296 }
297
298 /**
299 * @param {string} selector
300 * @param {function()|string} pageFunction
301 * @param {!Array<*>} args
302 * @return {!Promise<(!Object|undefined)>}
303 */
304 async $eval(selector, pageFunction, ...args) {
305 return this.mainFrame().$eval(selector, pageFunction, ...args);
306 }
307
308 /**
309 * @param {string} selector
310 * @param {Function|string} pageFunction
311 * @param {!Array<*>} args
312 * @return {!Promise<(!Object|undefined)>}
313 */
314 async $$eval(selector, pageFunction, ...args) {
315 return this.mainFrame().$$eval(selector, pageFunction, ...args);
316 }
317
318 /**
319 * @param {string} selector
320 * @return {!Promise<!Array<!Puppeteer.ElementHandle>>}
321 */
322 async $$(selector) {
323 return this.mainFrame().$$(selector);
324 }
325
326 /**
327 * @param {string} expression
328 * @return {!Promise<!Array<!Puppeteer.ElementHandle>>}
329 */
330 async $x(expression) {
331 return this.mainFrame().$x(expression);
332 }
333
334 /**
335 * @param {!Array<string>} urls
336 * @return {!Promise<!Array<Network.Cookie>>}
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 * @param {Array<Network.CookieParam>} cookies
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 * @param {Array<Network.CookieParam>} cookies
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 * @param {Object} options
384 * @return {!Promise<!Puppeteer.ElementHandle>}
385 */
386 async addScriptTag(options) {
387 return this.mainFrame().addScriptTag(options);
388 }
389
390 /**
391 * @param {Object} options
392 * @return {!Promise<!Puppeteer.ElementHandle>}
393 */
394 async addStyleTag(options) {
395 return this.mainFrame().addStyleTag(options);
396 }
397
398 /**
399 * @param {string} name
400 * @param {function(?)} puppeteerFunction
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 * @param {?{username: string, password: string}} credentials
432 */
433 async authenticate(credentials) {
434 return this._networkManager.authenticate(credentials);
435 }
436
437 /**
438 * @param {!Object<string, string>} headers
439 */
440 async setExtraHTTPHeaders(headers) {
441 return this._networkManager.setExtraHTTPHeaders(headers);
442 }
443
444 /**
445 * @param {string} userAgent
446 */
447 async setUserAgent(userAgent) {
448 return this._networkManager.setUserAgent(userAgent);
449 }
450
451 /**
452 * @return {!Promise<!Object>}
453 */
454 async metrics() {
455 const response = await this._client.send('Performance.getMetrics');
456 return this._buildMetricsObject(response.metrics);
457 }
458
459 /**
460 * @param {*} event
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 * @param {?Array<!Protocol.Performance.Metric>} metrics
471 * @return {!Object}
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 * @param {!Protocol.Runtime.ExceptionDetails} exceptionDetails
484 */
485 _handleException(exceptionDetails) {
486 const message = helper.getExceptionMessage(exceptionDetails);
487 const err = new Error(message);
488 err.stack = ''; // Don't report clientside error with a node stack attached
489 this.emit(Page.Events.PageError, err);
490 }
491
492 /**
493 * @param {!Protocol.Runtime.consoleAPICalledPayload} event
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 * @param {!Protocol.Runtime.bindingCalledPayload} event
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 * @param {string} type
518 * @param {!Array<!Puppeteer.JSHandle>} args
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 * @return {!string}
554 */
555 url() {
556 return this.mainFrame().url();
557 }
558
559 /**
560 * @return {!Promise<String>}
561 */
562 async content() {
563 return await this._frameManager.mainFrame().content();
564 }
565
566 /**
567 * @param {string} html
568 */
569 async setContent(html) {
570 await this._frameManager.mainFrame().setContent(html);
571 }
572
573 /**
574 * @param {string} url
575 * @param {!Object=} options
576 * @return {!Promise<?Puppeteer.Response>}
577 */
578 async goto(url, options = {}) {
579 return await this._frameManager.mainFrame().goto(url, options);
580 }
581
582 /**
583 * @param {!Object=} options
584 * @return {!Promise<?Puppeteer.Response>}
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 * @param {!Object=} options
596 * @return {!Promise<?Puppeteer.Response>}
597 */
598 async waitForNavigation(options = {}) {
599 return await this._frameManager.mainFrame().waitForNavigation(options);
600 }
601
602 /**
603 * @param {(string|Function)} urlOrPredicate
604 * @param {!Object=} options
605 * @return {!Promise<!Puppeteer.Request>}
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 * @param {(string|Function)} urlOrPredicate
620 * @param {!Object=} options
621 * @return {!Promise<!Puppeteer.Response>}
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 * @param {!Object=} options
636 * @return {!Promise<?Puppeteer.Response>}
637 */
638 async goBack(options) {
639 return this._go(-1, options);
640 }
641
642 /**
643 * @param {!Object=} options
644 * @return {!Promise<?Puppeteer.Response>}
645 */
646 async goForward(options) {
647 return this._go(+1, options);
648 }
649
650 /**
651 * @param {!Object=} options
652 * @return {!Promise<?Puppeteer.Response>}
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 * @param {!Object} options
672 */
673 async emulate(options) {
674 return Promise.all([
675 this.setViewport(options.viewport),
676 this.setUserAgent(options.userAgent)
677 ]);
678 }
679
680 /**
681 * @param {boolean} enabled
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 * @param {boolean} enabled
692 */
693 async setBypassCSP(enabled) {
694 await this._client.send('Page.setBypassCSP', { enabled });
695 }
696
697 /**
698 * @param {?string} mediaType
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 * @param {!Puppeteer.Viewport} viewport
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 * @return {?Puppeteer.Viewport}
717 */
718 viewport() {
719 return this._viewport;
720 }
721
722 /**
723 * @param {function()|string} pageFunction
724 * @param {!Array<*>} args
725 * @return {!Promise<*>}
726 */
727 async evaluate(pageFunction, ...args) {
728 return this._frameManager.mainFrame().evaluate(pageFunction, ...args);
729 }
730
731 /**
732 * @param {function()|string} pageFunction
733 * @param {!Array<*>} args
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 * @param {Boolean} enabled
742 * @returns {!Promise}
743 */
744 async setCacheEnabled(enabled = true) {
745 await this._client.send('Network.setCacheDisabled', {cacheDisabled: !enabled});
746 }
747
748 /**
749 * @param {!Object=} options
750 * @return {!Promise<!Buffer|!String>}
751 */
752 async screenshot(options = {}) {
753 let screenshotType = null;
754 // options.type takes precedence over inferring the type from options.path
755 // because it may be a 0-length file with no extension created beforehand (i.e. as a temp file).
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 * @param {"png"|"jpeg"} format
789 * @param {!Object=} options
790 * @return {!Promise<!Buffer|!String>}
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 // Overwrite clip for full page at all times.
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 /** @type {!Protocol.Emulation.ScreenOrientation} */
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 * @param {!Object=} options
831 * @return {!Promise<!Buffer>}
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 * @return {!Promise<string>}
885 */
886 async title() {
887 return this.mainFrame().title();
888 }
889
890 /**
891 * @param {!{runBeforeUnload: (boolean|undefined)}=} options
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 * @return {boolean}
906 */
907 isClosed() {
908 return this._closed;
909 }
910
911 /**
912 * @return {!Mouse}
913 */
914 get mouse() {
915 return this._mouse;
916 }
917
918 /**
919 * @param {string} selector
920 * @param {!Object=} options
921 */
922 click(selector, options = {}) {
923 return this.mainFrame().click(selector, options);
924 }
925
926 /**
927 * @param {string} selector
928 */
929 focus(selector) {
930 return this.mainFrame().focus(selector);
931 }
932
933 /**
934 * @param {string} selector
935 */
936 hover(selector) {
937 return this.mainFrame().hover(selector);
938 }
939
940 /**
941 * @param {string} selector
942 * @param {!Array<string>} values
943 * @return {!Promise<!Array<string>>}
944 */
945 select(selector, ...values) {
946 return this.mainFrame().select(selector, ...values);
947 }
948
949 /**
950 * @param {string} selector
951 */
952 tap(selector) {
953 return this.mainFrame().tap(selector);
954 }
955
956 /**
957 * @param {string} selector
958 * @param {string} text
959 * @param {{delay: (number|undefined)}=} options
960 */
961 type(selector, text, options) {
962 return this.mainFrame().type(selector, text, options);
963 }
964
965 /**
966 * @param {(string|number|Function)} selectorOrFunctionOrTimeout
967 * @param {!Object=} options
968 * @param {!Array<*>} args
969 * @return {!Promise}
970 */
971 waitFor(selectorOrFunctionOrTimeout, options = {}, ...args) {
972 return this.mainFrame().waitFor(selectorOrFunctionOrTimeout, options, ...args);
973 }
974
975 /**
976 * @param {string} selector
977 * @param {!Object=} options
978 * @return {!Promise}
979 */
980 waitForSelector(selector, options = {}) {
981 return this.mainFrame().waitForSelector(selector, options);
982 }
983
984 /**
985 * @param {string} xpath
986 * @param {!Object=} options
987 * @return {!Promise}
988 */
989 waitForXPath(xpath, options = {}) {
990 return this.mainFrame().waitForXPath(xpath, options);
991 }
992
993 /**
994 * @param {function()} pageFunction
995 * @param {!Object=} options
996 * @param {!Array<*>} args
997 * @return {!Promise}
998 */
999 waitForFunction(pageFunction, options = {}, ...args) {
1000 return this.mainFrame().waitForFunction(pageFunction, options, ...args);
1001 }
1002}
1003
1004/** @type {!Set<string>} */
1005const 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/** @enum {string} */
1022Page.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
1036const unitToPixels = {
1037 'px': 1,
1038 'in': 96,
1039 'cm': 37.8,
1040 'mm': 3.78
1041};
1042
1043/**
1044 * @param {(string|number|undefined)} parameter
1045 * @return {(number|undefined)}
1046 */
1047function convertPrintParameterToInches(parameter) {
1048 if (typeof parameter === 'undefined')
1049 return undefined;
1050 let pixels;
1051 if (helper.isNumber(parameter)) {
1052 // Treat numbers as pixel values to be aligned with phantom's paperSize.
1053 pixels = /** @type {number} */ (parameter);
1054 } else if (helper.isString(parameter)) {
1055 const text = /** @type {string} */ (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 // In case of unknown unit try to parse the whole parameter as number of pixels.
1062 // This is consistent with phantom's paperSize behavior.
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
1075Page.Events = {
1076 Close: 'close',
1077 Console: 'console',
1078 Dialog: 'dialog',
1079 DOMContentLoaded: 'domcontentloaded',
1080 Error: 'error',
1081 // Can't use just 'error' due to node.js special treatment of error events.
1082 // @see https://nodejs.org/api/events.html#events_error_events
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 * @typedef {Object} Network.Cookie
1100 * @property {string} name
1101 * @property {string} value
1102 * @property {string} domain
1103 * @property {string} path
1104 * @property {number} expires
1105 * @property {number} size
1106 * @property {boolean} httpOnly
1107 * @property {boolean} secure
1108 * @property {boolean} session
1109 * @property {("Strict"|"Lax")=} sameSite
1110 */
1111
1112
1113/**
1114 * @typedef {Object} Network.CookieParam
1115 * @property {string} name
1116 * @property {string} value
1117 * @property {string=} url
1118 * @property {string=} domain
1119 * @property {string=} path
1120 * @property {number=} expires
1121 * @property {boolean=} httpOnly
1122 * @property {boolean=} secure
1123 * @property {("Strict"|"Lax")=} sameSite
1124 */
1125
1126class ConsoleMessage {
1127 /**
1128 * @param {string} type
1129 * @param {string} text
1130 * @param {!Array<!Puppeteer.JSHandle>} args
1131 */
1132 constructor(type, text, args = []) {
1133 this._type = type;
1134 this._text = text;
1135 this._args = args;
1136 }
1137
1138 /**
1139 * @return {string}
1140 */
1141 type() {
1142 return this._type;
1143 }
1144
1145 /**
1146 * @return {string}
1147 */
1148 text() {
1149 return this._text;
1150 }
1151
1152 /**
1153 * @return {!Array<!Puppeteer.JSHandle>}
1154 */
1155 args() {
1156 return this._args;
1157 }
1158}
1159
1160
1161module.exports = {Page};
1162helper.tracePublicAPI(Page);