UNPKG

32 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 => requests.set(request.url(), request))
498 ];
499
500 const mainFrame = this._frameManager.mainFrame();
501 const timeout = typeof options.timeout === 'number' ? options.timeout : this._defaultNavigationTimeout;
502 const watcher = new NavigatorWatcher(this._frameManager, mainFrame, timeout, options);
503 const navigationPromise = watcher.navigationPromise();
504 let error = await Promise.race([
505 navigate(this._client, url, referrer),
506 navigationPromise,
507 ]);
508 if (!error)
509 error = await navigationPromise;
510 watcher.cancel();
511 helper.removeEventListeners(eventListeners);
512 if (error)
513 throw error;
514 const request = requests.get(this.mainFrame().url());
515 return request ? request.response() : null;
516
517 /**
518 * @param {!Puppeteer.CDPSession} client
519 * @param {string} url
520 * @param {string} referrer
521 * @return {!Promise<?Error>}
522 */
523 async function navigate(client, url, referrer) {
524 try {
525 const response = await client.send('Page.navigate', {url, referrer});
526 return response.errorText ? new Error(response.errorText) : null;
527 } catch (error) {
528 return error;
529 }
530 }
531 }
532
533 /**
534 * @param {!Object=} options
535 * @return {!Promise<?Response>}
536 */
537 async reload(options) {
538 const [response] = await Promise.all([
539 this.waitForNavigation(options),
540 this._client.send('Page.reload')
541 ]);
542 return response;
543 }
544
545 /**
546 * @param {!Object=} options
547 * @return {!Promise<!Response>}
548 */
549 async waitForNavigation(options = {}) {
550 const mainFrame = this._frameManager.mainFrame();
551 const timeout = typeof options.timeout === 'number' ? options.timeout : this._defaultNavigationTimeout;
552 const watcher = new NavigatorWatcher(this._frameManager, mainFrame, timeout, options);
553
554 const responses = new Map();
555 const listener = helper.addEventListener(this._networkManager, NetworkManager.Events.Response, response => responses.set(response.url(), response));
556 const error = await watcher.navigationPromise();
557 helper.removeEventListeners([listener]);
558 if (error)
559 throw error;
560 return responses.get(this.mainFrame().url()) || null;
561 }
562
563 /**
564 * @param {!Object=} options
565 * @return {!Promise<?Response>}
566 */
567 async goBack(options) {
568 return this._go(-1, options);
569 }
570
571 /**
572 * @param {!Object=} options
573 * @return {!Promise<?Response>}
574 */
575 async goForward(options) {
576 return this._go(+1, options);
577 }
578
579 /**
580 * @param {!Object=} options
581 * @return {!Promise<?Response>}
582 */
583 async _go(delta, options) {
584 const history = await this._client.send('Page.getNavigationHistory');
585 const entry = history.entries[history.currentIndex + delta];
586 if (!entry)
587 return null;
588 const [response] = await Promise.all([
589 this.waitForNavigation(options),
590 this._client.send('Page.navigateToHistoryEntry', {entryId: entry.id}),
591 ]);
592 return response;
593 }
594
595 async bringToFront() {
596 await this._client.send('Page.bringToFront');
597 }
598
599 /**
600 * @param {!Object} options
601 */
602 async emulate(options) {
603 return Promise.all([
604 this.setViewport(options.viewport),
605 this.setUserAgent(options.userAgent)
606 ]);
607 }
608
609 /**
610 * @param {boolean} enabled
611 */
612 async setJavaScriptEnabled(enabled) {
613 await this._client.send('Emulation.setScriptExecutionDisabled', { value: !enabled });
614 }
615
616 /**
617 * @param {?string} mediaType
618 */
619 async emulateMedia(mediaType) {
620 console.assert(mediaType === 'screen' || mediaType === 'print' || mediaType === null, 'Unsupported media type: ' + mediaType);
621 await this._client.send('Emulation.setEmulatedMedia', {media: mediaType || ''});
622 }
623
624 /**
625 * @param {!Page.Viewport} viewport
626 */
627 async setViewport(viewport) {
628 const needsReload = await this._emulationManager.emulateViewport(this._client, viewport);
629 this._viewport = viewport;
630 if (needsReload)
631 await this.reload();
632 }
633
634 /**
635 * @return {!Page.Viewport}
636 */
637 viewport() {
638 return this._viewport;
639 }
640
641 /**
642 * @param {function()} pageFunction
643 * @param {!Array<*>} args
644 * @return {!Promise<*>}
645 */
646 async evaluate(pageFunction, ...args) {
647 return this._frameManager.mainFrame().evaluate(pageFunction, ...args);
648 }
649
650 /**
651 * @param {function()|string} pageFunction
652 * @param {!Array<*>} args
653 */
654 async evaluateOnNewDocument(pageFunction, ...args) {
655 const source = helper.evaluationString(pageFunction, ...args);
656 await this._client.send('Page.addScriptToEvaluateOnNewDocument', { source });
657 }
658
659 /**
660 * @param {!Object=} options
661 * @return {!Promise<!Buffer>}
662 */
663 async screenshot(options = {}) {
664 let screenshotType = null;
665 // options.type takes precedence over inferring the type from options.path
666 // because it may be a 0-length file with no extension created beforehand (i.e. as a temp file).
667 if (options.type) {
668 console.assert(options.type === 'png' || options.type === 'jpeg', 'Unknown options.type value: ' + options.type);
669 screenshotType = options.type;
670 } else if (options.path) {
671 const mimeType = mime.lookup(options.path);
672 if (mimeType === 'image/png')
673 screenshotType = 'png';
674 else if (mimeType === 'image/jpeg')
675 screenshotType = 'jpeg';
676 console.assert(screenshotType, 'Unsupported screenshot mime type: ' + mimeType);
677 }
678
679 if (!screenshotType)
680 screenshotType = 'png';
681
682 if (options.quality) {
683 console.assert(screenshotType === 'jpeg', 'options.quality is unsupported for the ' + screenshotType + ' screenshots');
684 console.assert(typeof options.quality === 'number', 'Expected options.quality to be a number but found ' + (typeof options.quality));
685 console.assert(Number.isInteger(options.quality), 'Expected options.quality to be an integer');
686 console.assert(options.quality >= 0 && options.quality <= 100, 'Expected options.quality to be between 0 and 100 (inclusive), got ' + options.quality);
687 }
688 console.assert(!options.clip || !options.fullPage, 'options.clip and options.fullPage are exclusive');
689 if (options.clip) {
690 console.assert(typeof options.clip.x === 'number', 'Expected options.clip.x to be a number but found ' + (typeof options.clip.x));
691 console.assert(typeof options.clip.y === 'number', 'Expected options.clip.y to be a number but found ' + (typeof options.clip.y));
692 console.assert(typeof options.clip.width === 'number', 'Expected options.clip.width to be a number but found ' + (typeof options.clip.width));
693 console.assert(typeof options.clip.height === 'number', 'Expected options.clip.height to be a number but found ' + (typeof options.clip.height));
694 }
695 return this._screenshotTaskQueue.postTask(this._screenshotTask.bind(this, screenshotType, options));
696 }
697
698 /**
699 * @param {string} format
700 * @param {!Object=} options
701 * @return {!Promise<!Buffer>}
702 */
703 async _screenshotTask(format, options) {
704 await this._client.send('Target.activateTarget', {targetId: this._target._targetId});
705 let clip = options.clip ? Object.assign({}, options['clip']) : undefined;
706 if (clip)
707 clip.scale = 1;
708
709 if (options.fullPage) {
710 const metrics = await this._client.send('Page.getLayoutMetrics');
711 const width = Math.ceil(metrics.contentSize.width);
712 const height = Math.ceil(metrics.contentSize.height);
713
714 // Overwrite clip for full page at all times.
715 clip = { x: 0, y: 0, width, height, scale: 1 };
716 const mobile = this._viewport.isMobile || false;
717 const deviceScaleFactor = this._viewport.deviceScaleFactor || 1;
718 const landscape = this._viewport.isLandscape || false;
719 const screenOrientation = landscape ? { angle: 90, type: 'landscapePrimary' } : { angle: 0, type: 'portraitPrimary' };
720 await this._client.send('Emulation.setDeviceMetricsOverride', { mobile, width, height, deviceScaleFactor, screenOrientation });
721 }
722
723 if (options.omitBackground)
724 await this._client.send('Emulation.setDefaultBackgroundColorOverride', { color: { r: 0, g: 0, b: 0, a: 0 } });
725 const result = await this._client.send('Page.captureScreenshot', { format, quality: options.quality, clip });
726 if (options.omitBackground)
727 await this._client.send('Emulation.setDefaultBackgroundColorOverride');
728
729 if (options.fullPage)
730 await this.setViewport(this._viewport);
731
732 const buffer = new Buffer(result.data, 'base64');
733 if (options.path)
734 await writeFileAsync(options.path, buffer);
735 return buffer;
736 }
737
738 /**
739 * @param {!Object=} options
740 * @return {!Promise<!Buffer>}
741 */
742 async pdf(options = {}) {
743 const scale = options.scale || 1;
744 const displayHeaderFooter = !!options.displayHeaderFooter;
745 const headerTemplate = options.headerTemplate || '';
746 const footerTemplate = options.footerTemplate || '';
747 const printBackground = !!options.printBackground;
748 const landscape = !!options.landscape;
749 const pageRanges = options.pageRanges || '';
750
751 let paperWidth = 8.5;
752 let paperHeight = 11;
753 if (options.format) {
754 const format = Page.PaperFormats[options.format.toLowerCase()];
755 console.assert(format, 'Unknown paper format: ' + options.format);
756 paperWidth = format.width;
757 paperHeight = format.height;
758 } else {
759 paperWidth = convertPrintParameterToInches(options.width) || paperWidth;
760 paperHeight = convertPrintParameterToInches(options.height) || paperHeight;
761 }
762
763 const marginOptions = options.margin || {};
764 const marginTop = convertPrintParameterToInches(marginOptions.top) || 0;
765 const marginLeft = convertPrintParameterToInches(marginOptions.left) || 0;
766 const marginBottom = convertPrintParameterToInches(marginOptions.bottom) || 0;
767 const marginRight = convertPrintParameterToInches(marginOptions.right) || 0;
768
769 const result = await this._client.send('Page.printToPDF', {
770 landscape: landscape,
771 displayHeaderFooter: displayHeaderFooter,
772 headerTemplate: headerTemplate,
773 footerTemplate: footerTemplate,
774 printBackground: printBackground,
775 scale: scale,
776 paperWidth: paperWidth,
777 paperHeight: paperHeight,
778 marginTop: marginTop,
779 marginBottom: marginBottom,
780 marginLeft: marginLeft,
781 marginRight: marginRight,
782 pageRanges: pageRanges
783 });
784 const buffer = new Buffer(result.data, 'base64');
785 if (options.path)
786 await writeFileAsync(options.path, buffer);
787 return buffer;
788 }
789
790 /**
791 * @return {!Promise<string>}
792 */
793 async title() {
794 return this.mainFrame().title();
795 }
796
797 async close() {
798 console.assert(!!this._client._connection, 'Protocol error: Connection closed. Most likely the page has been closed.');
799 await this._client._connection.send('Target.closeTarget', {targetId: this._target._targetId});
800 }
801
802 /**
803 * @return {!Mouse}
804 */
805 get mouse() {
806 return this._mouse;
807 }
808
809 /**
810 * @param {string} selector
811 * @param {!Object=} options
812 */
813 async click(selector, options = {}) {
814 const handle = await this.$(selector);
815 console.assert(handle, 'No node found for selector: ' + selector);
816 await handle.click(options);
817 await handle.dispose();
818 }
819
820 /**
821 * @param {string} selector
822 */
823 async hover(selector) {
824 const handle = await this.$(selector);
825 console.assert(handle, 'No node found for selector: ' + selector);
826 await handle.hover();
827 await handle.dispose();
828 }
829
830 /**
831 * @param {string} selector
832 */
833 async focus(selector) {
834 const handle = await this.$(selector);
835 console.assert(handle, 'No node found for selector: ' + selector);
836 await handle.focus();
837 await handle.dispose();
838 }
839
840 /**
841 * @param {string} selector
842 * @param {!Array<string>} values
843 * @return {!Promise<!Array<string>>}
844 */
845 async select(selector, ...values) {
846 return this.mainFrame().select(selector, ...values);
847 }
848
849 /**
850 * @param {string} selector
851 * @param {string} text
852 * @param {{delay: (number|undefined)}=} options
853 */
854 async type(selector, text, options) {
855 const handle = await this.$(selector);
856 console.assert(handle, 'No node found for selector: ' + selector);
857 await handle.type(text, options);
858 await handle.dispose();
859 }
860
861 /**
862 * @param {(string|number|Function)} selectorOrFunctionOrTimeout
863 * @param {!Object=} options
864 * @param {!Array<*>} args
865 * @return {!Promise}
866 */
867 waitFor(selectorOrFunctionOrTimeout, options = {}, ...args) {
868 return this.mainFrame().waitFor(selectorOrFunctionOrTimeout, options, ...args);
869 }
870
871 /**
872 * @param {string} selector
873 * @param {!Object=} options
874 * @return {!Promise}
875 */
876 waitForSelector(selector, options = {}) {
877 return this.mainFrame().waitForSelector(selector, options);
878 }
879
880 /**
881 * @param {function()} pageFunction
882 * @param {!Object=} options
883 * @param {!Array<*>} args
884 * @return {!Promise}
885 */
886 waitForFunction(pageFunction, options = {}, ...args) {
887 return this.mainFrame().waitForFunction(pageFunction, options, ...args);
888 }
889}
890
891/** @type {!Set<string>} */
892const supportedMetrics = new Set([
893 'Timestamp',
894 'Documents',
895 'Frames',
896 'JSEventListeners',
897 'Nodes',
898 'LayoutCount',
899 'RecalcStyleCount',
900 'LayoutDuration',
901 'RecalcStyleDuration',
902 'ScriptDuration',
903 'TaskDuration',
904 'JSHeapUsedSize',
905 'JSHeapTotalSize',
906]);
907
908/** @enum {string} */
909Page.PaperFormats = {
910 letter: {width: 8.5, height: 11},
911 legal: {width: 8.5, height: 14},
912 tabloid: {width: 11, height: 17},
913 ledger: {width: 17, height: 11},
914 a0: {width: 33.1, height: 46.8 },
915 a1: {width: 23.4, height: 33.1 },
916 a2: {width: 16.5, height: 23.4 },
917 a3: {width: 11.7, height: 16.5 },
918 a4: {width: 8.27, height: 11.7 },
919 a5: {width: 5.83, height: 8.27 },
920 a6: {width: 4.13, height: 5.83 },
921};
922
923const unitToPixels = {
924 'px': 1,
925 'in': 96,
926 'cm': 37.8,
927 'mm': 3.78
928};
929
930/**
931 * @param {(string|number|undefined)} parameter
932 * @return {(number|undefined)}
933 */
934function convertPrintParameterToInches(parameter) {
935 if (typeof parameter === 'undefined')
936 return undefined;
937 let pixels;
938 if (helper.isNumber(parameter)) {
939 // Treat numbers as pixel values to be aligned with phantom's paperSize.
940 pixels = /** @type {number} */ (parameter);
941 } else if (helper.isString(parameter)) {
942 const text = /** @type {string} */ (parameter);
943 let unit = text.substring(text.length - 2).toLowerCase();
944 let valueText = '';
945 if (unitToPixels.hasOwnProperty(unit)) {
946 valueText = text.substring(0, text.length - 2);
947 } else {
948 // In case of unknown unit try to parse the whole parameter as number of pixels.
949 // This is consistent with phantom's paperSize behavior.
950 unit = 'px';
951 valueText = text;
952 }
953 const value = Number(valueText);
954 console.assert(!isNaN(value), 'Failed to parse parameter value: ' + text);
955 pixels = value * unitToPixels[unit];
956 } else {
957 throw new Error('page.pdf() Cannot handle parameter type: ' + (typeof parameter));
958 }
959 return pixels / 96;
960}
961
962Page.Events = {
963 Console: 'console',
964 Dialog: 'dialog',
965 Error: 'error',
966 // Can't use just 'error' due to node.js special treatment of error events.
967 // @see https://nodejs.org/api/events.html#events_error_events
968 PageError: 'pageerror',
969 Request: 'request',
970 Response: 'response',
971 RequestFailed: 'requestfailed',
972 RequestFinished: 'requestfinished',
973 FrameAttached: 'frameattached',
974 FrameDetached: 'framedetached',
975 FrameNavigated: 'framenavigated',
976 Load: 'load',
977 Metrics: 'metrics',
978};
979
980/**
981 * @typedef {Object} Page.Viewport
982 * @property {number} width
983 * @property {number} height
984 * @property {number=} deviceScaleFactor
985 * @property {boolean=} isMobile
986 * @property {boolean=} isLandscape
987 * @property {boolean=} hasTouch
988 */
989
990/**
991 * @typedef {Object} Network.Cookie
992 * @property {string} name
993 * @property {string} value
994 * @property {string} domain
995 * @property {string} path
996 * @property {number} expires
997 * @property {number} size
998 * @property {boolean} httpOnly
999 * @property {boolean} secure
1000 * @property {boolean} session
1001 * @property {("Strict"|"Lax")=} sameSite
1002 */
1003
1004
1005/**
1006 * @typedef {Object} Network.CookieParam
1007 * @property {string} name
1008 * @property {string=} value
1009 * @property {string=} url
1010 * @property {string=} domain
1011 * @property {string=} path
1012 * @property {number=} expires
1013 * @property {boolean=} httpOnly
1014 * @property {boolean=} secure
1015 * @property {("Strict"|"Lax")=} sameSite
1016 */
1017
1018class ConsoleMessage {
1019 /**
1020 * @param {string} type
1021 * @param {string} text
1022 * @param {!Array<*>} args
1023 */
1024 constructor(type, text, args) {
1025 this._type = type;
1026 this._text = text;
1027 this._args = args;
1028 }
1029
1030 /**
1031 * @return {string}
1032 */
1033 type() {
1034 return this._type;
1035 }
1036
1037 /**
1038 * @return {string}
1039 */
1040 text() {
1041 return this._text;
1042 }
1043
1044 /**
1045 * @return {!Array<string>}
1046 */
1047 args() {
1048 return this._args;
1049 }
1050}
1051
1052
1053module.exports = Page;
1054helper.tracePublicAPI(Page);