UNPKG

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