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, 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 |
|
57 | if (!appMode)
|
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.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 |
|
109 |
|
110 | target() {
|
111 | return this._target;
|
112 | }
|
113 |
|
114 | _onTargetCrashed() {
|
115 | this.emit('error', new Error('Page crashed!'));
|
116 | }
|
117 |
|
118 | |
119 |
|
120 |
|
121 | mainFrame() {
|
122 | return this._frameManager.mainFrame();
|
123 | }
|
124 |
|
125 | |
126 |
|
127 |
|
128 | get keyboard() {
|
129 | return this._keyboard;
|
130 | }
|
131 |
|
132 | |
133 |
|
134 |
|
135 | get touchscreen() {
|
136 | return this._touchscreen;
|
137 | }
|
138 |
|
139 | |
140 |
|
141 |
|
142 | get coverage() {
|
143 | return this._coverage;
|
144 | }
|
145 |
|
146 | |
147 |
|
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 |
|
158 |
|
159 | get tracing() {
|
160 | return this._tracing;
|
161 | }
|
162 |
|
163 | |
164 |
|
165 |
|
166 | frames() {
|
167 | return this._frameManager.frames();
|
168 | }
|
169 |
|
170 | |
171 |
|
172 |
|
173 | async setRequestInterception(value) {
|
174 | return this._networkManager.setRequestInterception(value);
|
175 | }
|
176 |
|
177 | |
178 |
|
179 |
|
180 | setOfflineMode(enabled) {
|
181 | return this._networkManager.setOfflineMode(enabled);
|
182 | }
|
183 |
|
184 | |
185 |
|
186 |
|
187 | setDefaultNavigationTimeout(timeout) {
|
188 | this._defaultNavigationTimeout = timeout;
|
189 | }
|
190 |
|
191 | |
192 |
|
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 |
|
205 |
|
206 |
|
207 | async $(selector) {
|
208 | return this.mainFrame().$(selector);
|
209 | }
|
210 |
|
211 | |
212 |
|
213 |
|
214 |
|
215 |
|
216 | async evaluateHandle(pageFunction, ...args) {
|
217 | const context = await this.mainFrame().executionContext();
|
218 | return context.evaluateHandle(pageFunction, ...args);
|
219 | }
|
220 |
|
221 | |
222 |
|
223 |
|
224 |
|
225 | async queryObjects(prototypeHandle) {
|
226 | const context = await this.mainFrame().executionContext();
|
227 | return context.queryObjects(prototypeHandle);
|
228 | }
|
229 |
|
230 | |
231 |
|
232 |
|
233 |
|
234 |
|
235 |
|
236 | async $eval(selector, pageFunction, ...args) {
|
237 | return this.mainFrame().$eval(selector, pageFunction, ...args);
|
238 | }
|
239 |
|
240 | |
241 |
|
242 |
|
243 |
|
244 |
|
245 |
|
246 | async $$eval(selector, pageFunction, ...args) {
|
247 | return this.mainFrame().$$eval(selector, pageFunction, ...args);
|
248 | }
|
249 |
|
250 | |
251 |
|
252 |
|
253 |
|
254 | async $$(selector) {
|
255 | return this.mainFrame().$$(selector);
|
256 | }
|
257 |
|
258 | |
259 |
|
260 |
|
261 |
|
262 | async $x(expression) {
|
263 | return this.mainFrame().$x(expression);
|
264 | }
|
265 |
|
266 | |
267 |
|
268 |
|
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 |
|
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 |
|
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 |
|
316 |
|
317 |
|
318 | async addScriptTag(options) {
|
319 | return this.mainFrame().addScriptTag(options);
|
320 | }
|
321 |
|
322 | |
323 |
|
324 |
|
325 |
|
326 | async addStyleTag(options) {
|
327 | return this.mainFrame().addStyleTag(options);
|
328 | }
|
329 |
|
330 | |
331 |
|
332 |
|
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 |
|
355 | console.debug('driver:page-binding', JSON.stringify({name: bindingName, seq, args}));
|
356 | return promise;
|
357 | };
|
358 | }
|
359 | }
|
360 |
|
361 | |
362 |
|
363 |
|
364 | async authenticate(credentials) {
|
365 | return this._networkManager.authenticate(credentials);
|
366 | }
|
367 |
|
368 | |
369 |
|
370 |
|
371 | async setExtraHTTPHeaders(headers) {
|
372 | return this._networkManager.setExtraHTTPHeaders(headers);
|
373 | }
|
374 |
|
375 | |
376 |
|
377 |
|
378 | async setUserAgent(userAgent) {
|
379 | return this._networkManager.setUserAgent(userAgent);
|
380 | }
|
381 |
|
382 | |
383 |
|
384 |
|
385 | async metrics() {
|
386 | const response = await this._client.send('Performance.getMetrics');
|
387 | return this._buildMetricsObject(response.metrics);
|
388 | }
|
389 |
|
390 | |
391 |
|
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 |
|
402 |
|
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 |
|
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 |
|
468 |
|
469 | url() {
|
470 | return this.mainFrame().url();
|
471 | }
|
472 |
|
473 | |
474 |
|
475 |
|
476 | async content() {
|
477 | return await this._frameManager.mainFrame().content();
|
478 | }
|
479 |
|
480 | |
481 |
|
482 |
|
483 | async setContent(html) {
|
484 | await this._frameManager.mainFrame().setContent(html);
|
485 | }
|
486 |
|
487 | |
488 |
|
489 |
|
490 |
|
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 |
|
522 |
|
523 |
|
524 |
|
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 |
|
538 |
|
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 |
|
550 |
|
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 |
|
568 |
|
569 |
|
570 | async goBack(options) {
|
571 | return this._go(-1, options);
|
572 | }
|
573 |
|
574 | |
575 |
|
576 |
|
577 |
|
578 | async goForward(options) {
|
579 | return this._go(+1, options);
|
580 | }
|
581 |
|
582 | |
583 |
|
584 |
|
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 |
|
604 |
|
605 | async emulate(options) {
|
606 | return Promise.all([
|
607 | this.setViewport(options.viewport),
|
608 | this.setUserAgent(options.userAgent)
|
609 | ]);
|
610 | }
|
611 |
|
612 | |
613 |
|
614 |
|
615 | async setJavaScriptEnabled(enabled) {
|
616 | await this._client.send('Emulation.setScriptExecutionDisabled', { value: !enabled });
|
617 | }
|
618 |
|
619 | |
620 |
|
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 |
|
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 |
|
639 |
|
640 | viewport() {
|
641 | return this._viewport;
|
642 | }
|
643 |
|
644 | |
645 |
|
646 |
|
647 |
|
648 |
|
649 | async evaluate(pageFunction, ...args) {
|
650 | return this._frameManager.mainFrame().evaluate(pageFunction, ...args);
|
651 | }
|
652 |
|
653 | |
654 |
|
655 |
|
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 |
|
664 |
|
665 |
|
666 | async screenshot(options = {}) {
|
667 | let screenshotType = null;
|
668 |
|
669 |
|
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 |
|
703 |
|
704 |
|
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 |
|
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 |
|
743 |
|
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 |
|
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 |
|
807 |
|
808 | get mouse() {
|
809 | return this._mouse;
|
810 | }
|
811 |
|
812 | |
813 |
|
814 |
|
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 |
|
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 |
|
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 |
|
845 |
|
846 |
|
847 |
|
848 | async select(selector, ...values) {
|
849 | return this.mainFrame().select(selector, ...values);
|
850 | }
|
851 |
|
852 | |
853 |
|
854 |
|
855 |
|
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 |
|
866 |
|
867 |
|
868 |
|
869 |
|
870 | waitFor(selectorOrFunctionOrTimeout, options = {}, ...args) {
|
871 | return this.mainFrame().waitFor(selectorOrFunctionOrTimeout, options, ...args);
|
872 | }
|
873 |
|
874 | |
875 |
|
876 |
|
877 |
|
878 |
|
879 | waitForSelector(selector, options = {}) {
|
880 | return this.mainFrame().waitForSelector(selector, options);
|
881 | }
|
882 |
|
883 | |
884 |
|
885 |
|
886 |
|
887 |
|
888 |
|
889 | waitForFunction(pageFunction, options = {}, ...args) {
|
890 | return this.mainFrame().waitForFunction(pageFunction, options, ...args);
|
891 | }
|
892 | }
|
893 |
|
894 |
|
895 | const 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 |
|
912 | Page.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 |
|
926 | const unitToPixels = {
|
927 | 'px': 1,
|
928 | 'in': 96,
|
929 | 'cm': 37.8,
|
930 | 'mm': 3.78
|
931 | };
|
932 |
|
933 |
|
934 |
|
935 |
|
936 |
|
937 | function convertPrintParameterToInches(parameter) {
|
938 | if (typeof parameter === 'undefined')
|
939 | return undefined;
|
940 | let pixels;
|
941 | if (helper.isNumber(parameter)) {
|
942 |
|
943 | pixels = (parameter);
|
944 | } else if (helper.isString(parameter)) {
|
945 | const text = (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 |
|
952 |
|
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 |
|
965 | Page.Events = {
|
966 | Console: 'console',
|
967 | Dialog: 'dialog',
|
968 | Error: 'error',
|
969 |
|
970 |
|
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 |
|
985 |
|
986 |
|
987 |
|
988 |
|
989 |
|
990 |
|
991 |
|
992 |
|
993 |
|
994 |
|
995 |
|
996 |
|
997 |
|
998 |
|
999 |
|
1000 |
|
1001 |
|
1002 |
|
1003 |
|
1004 |
|
1005 |
|
1006 |
|
1007 |
|
1008 |
|
1009 |
|
1010 |
|
1011 |
|
1012 |
|
1013 |
|
1014 |
|
1015 |
|
1016 |
|
1017 |
|
1018 |
|
1019 |
|
1020 |
|
1021 | class ConsoleMessage {
|
1022 | |
1023 |
|
1024 |
|
1025 |
|
1026 |
|
1027 | constructor(type, text, args) {
|
1028 | this._type = type;
|
1029 | this._text = text;
|
1030 | this._args = args;
|
1031 | }
|
1032 |
|
1033 | |
1034 |
|
1035 |
|
1036 | type() {
|
1037 | return this._type;
|
1038 | }
|
1039 |
|
1040 | |
1041 |
|
1042 |
|
1043 | text() {
|
1044 | return this._text;
|
1045 | }
|
1046 |
|
1047 | |
1048 |
|
1049 |
|
1050 | args() {
|
1051 | return this._args;
|
1052 | }
|
1053 | }
|
1054 |
|
1055 |
|
1056 | module.exports = Page;
|
1057 | helper.tracePublicAPI(Page);
|