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 const metrics = await this._client.send('Page.getLayoutMetrics');
800 const width = Math.ceil(metrics.contentSize.width);
801 const height = Math.ceil(metrics.contentSize.height);
802
803 // Overwrite clip for full page at all times.
804 clip = { x: 0, y: 0, width, height, scale: 1 };
805 const {
806 isMobile = false,
807 deviceScaleFactor = 1,
808 isLandscape = false
809 } = this._viewport || {};
810 /** @type {!Protocol.Emulation.ScreenOrientation} */
811 const screenOrientation = isLandscape ? { angle: 90, type: 'landscapePrimary' } : { angle: 0, type: 'portraitPrimary' };
812 await this._client.send('Emulation.setDeviceMetricsOverride', { mobile: isMobile, width, height, deviceScaleFactor, screenOrientation });
813 }
814 const shouldSetDefaultBackground = options.omitBackground && format === 'png';
815 if (shouldSetDefaultBackground)
816 await this._client.send('Emulation.setDefaultBackgroundColorOverride', { color: { r: 0, g: 0, b: 0, a: 0 } });
817 const result = await this._client.send('Page.captureScreenshot', { format, quality: options.quality, clip });
818 if (shouldSetDefaultBackground)
819 await this._client.send('Emulation.setDefaultBackgroundColorOverride');
820
821 if (options.fullPage && this._viewport)
822 await this.setViewport(this._viewport);
823
824 const buffer = options.encoding === 'base64' ? result.data : Buffer.from(result.data, 'base64');
825 if (options.path)
826 await writeFileAsync(options.path, buffer);
827 return buffer;
828 }
829
830 /**
831 * @param {!Object=} options
832 * @return {!Promise<!Buffer>}
833 */
834 async pdf(options = {}) {
835 const scale = options.scale || 1;
836 const displayHeaderFooter = !!options.displayHeaderFooter;
837 const headerTemplate = options.headerTemplate || '';
838 const footerTemplate = options.footerTemplate || '';
839 const printBackground = !!options.printBackground;
840 const landscape = !!options.landscape;
841 const pageRanges = options.pageRanges || '';
842
843 let paperWidth = 8.5;
844 let paperHeight = 11;
845 if (options.format) {
846 const format = Page.PaperFormats[options.format.toLowerCase()];
847 assert(format, 'Unknown paper format: ' + options.format);
848 paperWidth = format.width;
849 paperHeight = format.height;
850 } else {
851 paperWidth = convertPrintParameterToInches(options.width) || paperWidth;
852 paperHeight = convertPrintParameterToInches(options.height) || paperHeight;
853 }
854
855 const marginOptions = options.margin || {};
856 const marginTop = convertPrintParameterToInches(marginOptions.top) || 0;
857 const marginLeft = convertPrintParameterToInches(marginOptions.left) || 0;
858 const marginBottom = convertPrintParameterToInches(marginOptions.bottom) || 0;
859 const marginRight = convertPrintParameterToInches(marginOptions.right) || 0;
860 const preferCSSPageSize = options.preferCSSPageSize || false;
861
862 const result = await this._client.send('Page.printToPDF', {
863 landscape: landscape,
864 displayHeaderFooter: displayHeaderFooter,
865 headerTemplate: headerTemplate,
866 footerTemplate: footerTemplate,
867 printBackground: printBackground,
868 scale: scale,
869 paperWidth: paperWidth,
870 paperHeight: paperHeight,
871 marginTop: marginTop,
872 marginBottom: marginBottom,
873 marginLeft: marginLeft,
874 marginRight: marginRight,
875 pageRanges: pageRanges,
876 preferCSSPageSize: preferCSSPageSize
877 });
878 const buffer = Buffer.from(result.data, 'base64');
879 if (options.path)
880 await writeFileAsync(options.path, buffer);
881 return buffer;
882 }
883
884 /**
885 * @return {!Promise<string>}
886 */
887 async title() {
888 return this.mainFrame().title();
889 }
890
891 /**
892 * @param {!{runBeforeUnload: (boolean|undefined)}=} options
893 */
894 async close(options = {runBeforeUnload: undefined}) {
895 assert(!!this._client._connection, 'Protocol error: Connection closed. Most likely the page has been closed.');
896 const runBeforeUnload = !!options.runBeforeUnload;
897 if (runBeforeUnload) {
898 await this._client.send('Page.close');
899 } else {
900 await this._client._connection.send('Target.closeTarget', { targetId: this._target._targetId });
901 await this._target._isClosedPromise;
902 }
903 }
904
905 /**
906 * @return {boolean}
907 */
908 isClosed() {
909 return this._closed;
910 }
911
912 /**
913 * @return {!Mouse}
914 */
915 get mouse() {
916 return this._mouse;
917 }
918
919 /**
920 * @param {string} selector
921 * @param {!Object=} options
922 */
923 click(selector, options = {}) {
924 return this.mainFrame().click(selector, options);
925 }
926
927 /**
928 * @param {string} selector
929 */
930 focus(selector) {
931 return this.mainFrame().focus(selector);
932 }
933
934 /**
935 * @param {string} selector
936 */
937 hover(selector) {
938 return this.mainFrame().hover(selector);
939 }
940
941 /**
942 * @param {string} selector
943 * @param {!Array<string>} values
944 * @return {!Promise<!Array<string>>}
945 */
946 select(selector, ...values) {
947 return this.mainFrame().select(selector, ...values);
948 }
949
950 /**
951 * @param {string} selector
952 */
953 tap(selector) {
954 return this.mainFrame().tap(selector);
955 }
956
957 /**
958 * @param {string} selector
959 * @param {string} text
960 * @param {{delay: (number|undefined)}=} options
961 */
962 type(selector, text, options) {
963 return this.mainFrame().type(selector, text, options);
964 }
965
966 /**
967 * @param {(string|number|Function)} selectorOrFunctionOrTimeout
968 * @param {!Object=} options
969 * @param {!Array<*>} args
970 * @return {!Promise}
971 */
972 waitFor(selectorOrFunctionOrTimeout, options = {}, ...args) {
973 return this.mainFrame().waitFor(selectorOrFunctionOrTimeout, options, ...args);
974 }
975
976 /**
977 * @param {string} selector
978 * @param {!Object=} options
979 * @return {!Promise}
980 */
981 waitForSelector(selector, options = {}) {
982 return this.mainFrame().waitForSelector(selector, options);
983 }
984
985 /**
986 * @param {string} xpath
987 * @param {!Object=} options
988 * @return {!Promise}
989 */
990 waitForXPath(xpath, options = {}) {
991 return this.mainFrame().waitForXPath(xpath, options);
992 }
993
994 /**
995 * @param {function()} pageFunction
996 * @param {!Object=} options
997 * @param {!Array<*>} args
998 * @return {!Promise}
999 */
1000 waitForFunction(pageFunction, options = {}, ...args) {
1001 return this.mainFrame().waitForFunction(pageFunction, options, ...args);
1002 }
1003}
1004
1005/** @type {!Set<string>} */
1006const supportedMetrics = new Set([
1007 'Timestamp',
1008 'Documents',
1009 'Frames',
1010 'JSEventListeners',
1011 'Nodes',
1012 'LayoutCount',
1013 'RecalcStyleCount',
1014 'LayoutDuration',
1015 'RecalcStyleDuration',
1016 'ScriptDuration',
1017 'TaskDuration',
1018 'JSHeapUsedSize',
1019 'JSHeapTotalSize',
1020]);
1021
1022/** @enum {!{width: number, height: number}} */
1023Page.PaperFormats = {
1024 letter: {width: 8.5, height: 11},
1025 legal: {width: 8.5, height: 14},
1026 tabloid: {width: 11, height: 17},
1027 ledger: {width: 17, height: 11},
1028 a0: {width: 33.1, height: 46.8 },
1029 a1: {width: 23.4, height: 33.1 },
1030 a2: {width: 16.5, height: 23.4 },
1031 a3: {width: 11.7, height: 16.5 },
1032 a4: {width: 8.27, height: 11.7 },
1033 a5: {width: 5.83, height: 8.27 },
1034 a6: {width: 4.13, height: 5.83 },
1035};
1036
1037const unitToPixels = {
1038 'px': 1,
1039 'in': 96,
1040 'cm': 37.8,
1041 'mm': 3.78
1042};
1043
1044/**
1045 * @param {(string|number|undefined)} parameter
1046 * @return {(number|undefined)}
1047 */
1048function convertPrintParameterToInches(parameter) {
1049 if (typeof parameter === 'undefined')
1050 return undefined;
1051 let pixels;
1052 if (helper.isNumber(parameter)) {
1053 // Treat numbers as pixel values to be aligned with phantom's paperSize.
1054 pixels = /** @type {number} */ (parameter);
1055 } else if (helper.isString(parameter)) {
1056 const text = /** @type {string} */ (parameter);
1057 let unit = text.substring(text.length - 2).toLowerCase();
1058 let valueText = '';
1059 if (unitToPixels.hasOwnProperty(unit)) {
1060 valueText = text.substring(0, text.length - 2);
1061 } else {
1062 // In case of unknown unit try to parse the whole parameter as number of pixels.
1063 // This is consistent with phantom's paperSize behavior.
1064 unit = 'px';
1065 valueText = text;
1066 }
1067 const value = Number(valueText);
1068 assert(!isNaN(value), 'Failed to parse parameter value: ' + text);
1069 pixels = value * unitToPixels[unit];
1070 } else {
1071 throw new Error('page.pdf() Cannot handle parameter type: ' + (typeof parameter));
1072 }
1073 return pixels / 96;
1074}
1075
1076Page.Events = {
1077 Close: 'close',
1078 Console: 'console',
1079 Dialog: 'dialog',
1080 DOMContentLoaded: 'domcontentloaded',
1081 Error: 'error',
1082 // Can't use just 'error' due to node.js special treatment of error events.
1083 // @see https://nodejs.org/api/events.html#events_error_events
1084 PageError: 'pageerror',
1085 Request: 'request',
1086 Response: 'response',
1087 RequestFailed: 'requestfailed',
1088 RequestFinished: 'requestfinished',
1089 FrameAttached: 'frameattached',
1090 FrameDetached: 'framedetached',
1091 FrameNavigated: 'framenavigated',
1092 Load: 'load',
1093 Metrics: 'metrics',
1094 WorkerCreated: 'workercreated',
1095 WorkerDestroyed: 'workerdestroyed',
1096};
1097
1098
1099/**
1100 * @typedef {Object} Network.Cookie
1101 * @property {string} name
1102 * @property {string} value
1103 * @property {string} domain
1104 * @property {string} path
1105 * @property {number} expires
1106 * @property {number} size
1107 * @property {boolean} httpOnly
1108 * @property {boolean} secure
1109 * @property {boolean} session
1110 * @property {("Strict"|"Lax")=} sameSite
1111 */
1112
1113
1114/**
1115 * @typedef {Object} Network.CookieParam
1116 * @property {string} name
1117 * @property {string} value
1118 * @property {string=} url
1119 * @property {string=} domain
1120 * @property {string=} path
1121 * @property {number=} expires
1122 * @property {boolean=} httpOnly
1123 * @property {boolean=} secure
1124 * @property {("Strict"|"Lax")=} sameSite
1125 */
1126
1127class ConsoleMessage {
1128 /**
1129 * @param {string} type
1130 * @param {string} text
1131 * @param {!Array<!Puppeteer.JSHandle>} args
1132 */
1133 constructor(type, text, args = []) {
1134 this._type = type;
1135 this._text = text;
1136 this._args = args;
1137 }
1138
1139 /**
1140 * @return {string}
1141 */
1142 type() {
1143 return this._type;
1144 }
1145
1146 /**
1147 * @return {string}
1148 */
1149 text() {
1150 return this._text;
1151 }
1152
1153 /**
1154 * @return {!Array<!Puppeteer.JSHandle>}
1155 */
1156 args() {
1157 return this._args;
1158 }
1159}
1160
1161
1162module.exports = {Page};
1163helper.tracePublicAPI(Page);