UNPKG

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