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