1 |
|
2 |
|
3 |
|
4 |
|
5 |
|
6 |
|
7 |
|
8 |
|
9 |
|
10 |
|
11 |
|
12 |
|
13 |
|
14 |
|
15 |
|
16 |
|
17 | const fs = require('fs');
|
18 | const EventEmitter = require('events');
|
19 | const mime = require('mime');
|
20 | const {NetworkManager} = require('./NetworkManager');
|
21 | const NavigatorWatcher = require('./NavigatorWatcher');
|
22 | const Dialog = require('./Dialog');
|
23 | const EmulationManager = require('./EmulationManager');
|
24 | const {FrameManager} = require('./FrameManager');
|
25 | const {Keyboard, Mouse, Touchscreen} = require('./Input');
|
26 | const Tracing = require('./Tracing');
|
27 | const {helper, debugError} = require('./helper');
|
28 | const {Coverage} = require('./Coverage');
|
29 |
|
30 | const writeFileAsync = helper.promisify(fs.writeFile);
|
31 |
|
32 | class Page extends EventEmitter {
|
33 | |
34 |
|
35 |
|
36 |
|
37 |
|
38 |
|
39 |
|
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 |
|
57 | if (setDefaultViewport)
|
58 | await page.setViewport({width: 800, height: 600});
|
59 |
|
60 | return page;
|
61 | }
|
62 |
|
63 | |
64 |
|
65 |
|
66 |
|
67 |
|
68 |
|
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 |
|
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 |
|
112 |
|
113 | target() {
|
114 | return this._target;
|
115 | }
|
116 |
|
117 | _onTargetCrashed() {
|
118 | this.emit('error', new Error('Page crashed!'));
|
119 | }
|
120 |
|
121 | |
122 |
|
123 |
|
124 | mainFrame() {
|
125 | return this._frameManager.mainFrame();
|
126 | }
|
127 |
|
128 | |
129 |
|
130 |
|
131 | get keyboard() {
|
132 | return this._keyboard;
|
133 | }
|
134 |
|
135 | |
136 |
|
137 |
|
138 | get touchscreen() {
|
139 | return this._touchscreen;
|
140 | }
|
141 |
|
142 | |
143 |
|
144 |
|
145 | get coverage() {
|
146 | return this._coverage;
|
147 | }
|
148 |
|
149 | |
150 |
|
151 |
|
152 | get tracing() {
|
153 | return this._tracing;
|
154 | }
|
155 |
|
156 | |
157 |
|
158 |
|
159 | frames() {
|
160 | return this._frameManager.frames();
|
161 | }
|
162 |
|
163 | |
164 |
|
165 |
|
166 | async setRequestInterception(value) {
|
167 | return this._networkManager.setRequestInterception(value);
|
168 | }
|
169 |
|
170 | |
171 |
|
172 |
|
173 | setOfflineMode(enabled) {
|
174 | return this._networkManager.setOfflineMode(enabled);
|
175 | }
|
176 |
|
177 | |
178 |
|
179 |
|
180 | setDefaultNavigationTimeout(timeout) {
|
181 | this._defaultNavigationTimeout = timeout;
|
182 | }
|
183 |
|
184 | |
185 |
|
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 |
|
198 |
|
199 |
|
200 | async $(selector) {
|
201 | return this.mainFrame().$(selector);
|
202 | }
|
203 |
|
204 | |
205 |
|
206 |
|
207 |
|
208 |
|
209 | async evaluateHandle(pageFunction, ...args) {
|
210 | const context = await this.mainFrame().executionContext();
|
211 | return context.evaluateHandle(pageFunction, ...args);
|
212 | }
|
213 |
|
214 | |
215 |
|
216 |
|
217 |
|
218 | async queryObjects(prototypeHandle) {
|
219 | const context = await this.mainFrame().executionContext();
|
220 | return context.queryObjects(prototypeHandle);
|
221 | }
|
222 |
|
223 | |
224 |
|
225 |
|
226 |
|
227 |
|
228 |
|
229 | async $eval(selector, pageFunction, ...args) {
|
230 | return this.mainFrame().$eval(selector, pageFunction, ...args);
|
231 | }
|
232 |
|
233 | |
234 |
|
235 |
|
236 |
|
237 |
|
238 |
|
239 | async $$eval(selector, pageFunction, ...args) {
|
240 | return this.mainFrame().$$eval(selector, pageFunction, ...args);
|
241 | }
|
242 |
|
243 | |
244 |
|
245 |
|
246 |
|
247 | async $$(selector) {
|
248 | return this.mainFrame().$$(selector);
|
249 | }
|
250 |
|
251 | |
252 |
|
253 |
|
254 |
|
255 | async $x(expression) {
|
256 | return this.mainFrame().$x(expression);
|
257 | }
|
258 |
|
259 | |
260 |
|
261 |
|
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 |
|
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 |
|
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 |
|
309 |
|
310 |
|
311 | async addScriptTag(options) {
|
312 | return this.mainFrame().addScriptTag(options);
|
313 | }
|
314 |
|
315 | |
316 |
|
317 |
|
318 |
|
319 | async addStyleTag(options) {
|
320 | return this.mainFrame().addStyleTag(options);
|
321 | }
|
322 |
|
323 | |
324 |
|
325 |
|
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 |
|
348 | console.debug('driver:page-binding', JSON.stringify({name: bindingName, seq, args}));
|
349 | return promise;
|
350 | };
|
351 | }
|
352 | }
|
353 |
|
354 | |
355 |
|
356 |
|
357 | async authenticate(credentials) {
|
358 | return this._networkManager.authenticate(credentials);
|
359 | }
|
360 |
|
361 | |
362 |
|
363 |
|
364 | async setExtraHTTPHeaders(headers) {
|
365 | return this._networkManager.setExtraHTTPHeaders(headers);
|
366 | }
|
367 |
|
368 | |
369 |
|
370 |
|
371 | async setUserAgent(userAgent) {
|
372 | return this._networkManager.setUserAgent(userAgent);
|
373 | }
|
374 |
|
375 | |
376 |
|
377 |
|
378 | async metrics() {
|
379 | const response = await this._client.send('Performance.getMetrics');
|
380 | return this._buildMetricsObject(response.metrics);
|
381 | }
|
382 |
|
383 | |
384 |
|
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 |
|
395 |
|
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 |
|
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 |
|
461 |
|
462 | url() {
|
463 | return this.mainFrame().url();
|
464 | }
|
465 |
|
466 | |
467 |
|
468 |
|
469 | async content() {
|
470 | return await this._frameManager.mainFrame().content();
|
471 | }
|
472 |
|
473 | |
474 |
|
475 |
|
476 | async setContent(html) {
|
477 | await this._frameManager.mainFrame().setContent(html);
|
478 | }
|
479 |
|
480 | |
481 |
|
482 |
|
483 |
|
484 |
|
485 | async goto(url, options = {}) {
|
486 | const referrer = this._networkManager.extraHTTPHeaders()['referer'];
|
487 |
|
488 |
|
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 |
|
516 |
|
517 |
|
518 |
|
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 |
|
532 |
|
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 |
|
544 |
|
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 |
|
562 |
|
563 |
|
564 | async goBack(options) {
|
565 | return this._go(-1, options);
|
566 | }
|
567 |
|
568 | |
569 |
|
570 |
|
571 |
|
572 | async goForward(options) {
|
573 | return this._go(+1, options);
|
574 | }
|
575 |
|
576 | |
577 |
|
578 |
|
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 |
|
598 |
|
599 | async emulate(options) {
|
600 | return Promise.all([
|
601 | this.setViewport(options.viewport),
|
602 | this.setUserAgent(options.userAgent)
|
603 | ]);
|
604 | }
|
605 |
|
606 | |
607 |
|
608 |
|
609 | async setJavaScriptEnabled(enabled) {
|
610 | await this._client.send('Emulation.setScriptExecutionDisabled', { value: !enabled });
|
611 | }
|
612 |
|
613 | |
614 |
|
615 |
|
616 | async setBypassCSP(enabled) {
|
617 | await this._client.send('Page.setBypassCSP', { enabled });
|
618 | }
|
619 |
|
620 | |
621 |
|
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 |
|
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 |
|
640 |
|
641 | viewport() {
|
642 | return this._viewport;
|
643 | }
|
644 |
|
645 | |
646 |
|
647 |
|
648 |
|
649 |
|
650 | async evaluate(pageFunction, ...args) {
|
651 | return this._frameManager.mainFrame().evaluate(pageFunction, ...args);
|
652 | }
|
653 |
|
654 | |
655 |
|
656 |
|
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 |
|
665 |
|
666 |
|
667 | async setCacheEnabled(enabled = true) {
|
668 | await this._client.send('Network.setCacheDisabled', {cacheDisabled: !enabled});
|
669 | }
|
670 |
|
671 | |
672 |
|
673 |
|
674 |
|
675 | async screenshot(options = {}) {
|
676 | let screenshotType = null;
|
677 |
|
678 |
|
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 |
|
712 |
|
713 |
|
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 |
|
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 |
|
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 |
|
753 |
|
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 |
|
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 |
|
818 |
|
819 | get mouse() {
|
820 | return this._mouse;
|
821 | }
|
822 |
|
823 | |
824 |
|
825 |
|
826 |
|
827 | click(selector, options = {}) {
|
828 | return this.mainFrame().click(selector, options);
|
829 | }
|
830 |
|
831 | |
832 |
|
833 |
|
834 | focus(selector) {
|
835 | return this.mainFrame().focus(selector);
|
836 | }
|
837 |
|
838 | |
839 |
|
840 |
|
841 | hover(selector) {
|
842 | return this.mainFrame().hover(selector);
|
843 | }
|
844 |
|
845 | |
846 |
|
847 |
|
848 |
|
849 |
|
850 | select(selector, ...values) {
|
851 | return this.mainFrame().select(selector, ...values);
|
852 | }
|
853 |
|
854 | |
855 |
|
856 |
|
857 | tap(selector) {
|
858 | return this.mainFrame().tap(selector);
|
859 | }
|
860 |
|
861 | |
862 |
|
863 |
|
864 |
|
865 |
|
866 | type(selector, text, options) {
|
867 | return this.mainFrame().type(selector, text, options);
|
868 | }
|
869 |
|
870 | |
871 |
|
872 |
|
873 |
|
874 |
|
875 |
|
876 | waitFor(selectorOrFunctionOrTimeout, options = {}, ...args) {
|
877 | return this.mainFrame().waitFor(selectorOrFunctionOrTimeout, options, ...args);
|
878 | }
|
879 |
|
880 | |
881 |
|
882 |
|
883 |
|
884 |
|
885 | waitForSelector(selector, options = {}) {
|
886 | return this.mainFrame().waitForSelector(selector, options);
|
887 | }
|
888 |
|
889 | |
890 |
|
891 |
|
892 |
|
893 |
|
894 | waitForXPath(xpath, options = {}) {
|
895 | return this.mainFrame().waitForXPath(xpath, options);
|
896 | }
|
897 |
|
898 | |
899 |
|
900 |
|
901 |
|
902 |
|
903 |
|
904 | waitForFunction(pageFunction, options = {}, ...args) {
|
905 | return this.mainFrame().waitForFunction(pageFunction, options, ...args);
|
906 | }
|
907 | }
|
908 |
|
909 |
|
910 | const 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 |
|
927 | Page.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 |
|
941 | const unitToPixels = {
|
942 | 'px': 1,
|
943 | 'in': 96,
|
944 | 'cm': 37.8,
|
945 | 'mm': 3.78
|
946 | };
|
947 |
|
948 |
|
949 |
|
950 |
|
951 |
|
952 | function convertPrintParameterToInches(parameter) {
|
953 | if (typeof parameter === 'undefined')
|
954 | return undefined;
|
955 | let pixels;
|
956 | if (helper.isNumber(parameter)) {
|
957 |
|
958 | pixels = (parameter);
|
959 | } else if (helper.isString(parameter)) {
|
960 | const text = (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 |
|
967 |
|
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 |
|
980 | Page.Events = {
|
981 | Close: 'close',
|
982 | Console: 'console',
|
983 | Dialog: 'dialog',
|
984 | DOMContentLoaded: 'domcontentloaded',
|
985 | Error: 'error',
|
986 |
|
987 |
|
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 |
|
1002 |
|
1003 |
|
1004 |
|
1005 |
|
1006 |
|
1007 |
|
1008 |
|
1009 |
|
1010 |
|
1011 |
|
1012 |
|
1013 |
|
1014 |
|
1015 |
|
1016 |
|
1017 |
|
1018 |
|
1019 |
|
1020 |
|
1021 |
|
1022 |
|
1023 |
|
1024 |
|
1025 |
|
1026 |
|
1027 |
|
1028 |
|
1029 |
|
1030 |
|
1031 |
|
1032 |
|
1033 |
|
1034 |
|
1035 |
|
1036 |
|
1037 |
|
1038 | class ConsoleMessage {
|
1039 | |
1040 |
|
1041 |
|
1042 |
|
1043 |
|
1044 | constructor(type, text, args) {
|
1045 | this._type = type;
|
1046 | this._text = text;
|
1047 | this._args = args;
|
1048 | }
|
1049 |
|
1050 | |
1051 |
|
1052 |
|
1053 | type() {
|
1054 | return this._type;
|
1055 | }
|
1056 |
|
1057 | |
1058 |
|
1059 |
|
1060 | text() {
|
1061 | return this._text;
|
1062 | }
|
1063 |
|
1064 | |
1065 |
|
1066 |
|
1067 | args() {
|
1068 | return this._args;
|
1069 | }
|
1070 | }
|
1071 |
|
1072 |
|
1073 | module.exports = Page;
|
1074 | helper.tracePublicAPI(Page);
|