-
Notifications
You must be signed in to change notification settings - Fork 9.4k
/
driver.js
1232 lines (1094 loc) · 41.4 KB
/
driver.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/**
* @license Copyright 2016 Google Inc. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0
* Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License.
*/
// @ts-nocheck
'use strict';
const NetworkRecorder = require('../lib/network-recorder');
const emulation = require('../lib/emulation');
const Element = require('../lib/element');
const EventEmitter = require('events').EventEmitter;
const URL = require('../lib/url-shim');
const TraceParser = require('../lib/traces/trace-parser');
const log = require('lighthouse-logger');
const DevtoolsLog = require('./devtools-log');
// Controls how long to wait after onLoad before continuing
const DEFAULT_PAUSE_AFTER_LOAD = 0;
// Controls how long to wait between network requests before determining the network is quiet
const DEFAULT_NETWORK_QUIET_THRESHOLD = 5000;
// Controls how long to wait between longtasks before determining the CPU is idle, off by default
const DEFAULT_CPU_QUIET_THRESHOLD = 0;
const _uniq = arr => Array.from(new Set(arr));
class Driver {
static get MAX_WAIT_FOR_FULLY_LOADED() {
return 45 * 1000;
}
/**
* @param {!Connection} connection
*/
constructor(connection) {
this._traceEvents = [];
this._traceCategories = Driver.traceCategories;
this._eventEmitter = new EventEmitter();
this._connection = connection;
// currently only used by WPT where just Page and Network are needed
this._devtoolsLog = new DevtoolsLog(/^(Page|Network)\./);
this.online = true;
this._domainEnabledCounts = new Map();
this._isolatedExecutionContextId = undefined;
/**
* Used for monitoring network status events during gotoURL.
* @private {?NetworkRecorder}
*/
this._networkStatusMonitor = null;
/**
* Used for monitoring url redirects during gotoURL.
* @private {?string}
*/
this._monitoredUrl = null;
connection.on('notification', event => {
this._devtoolsLog.record(event);
if (this._networkStatusMonitor) {
this._networkStatusMonitor.dispatch(event.method, event.params);
}
this._eventEmitter.emit(event.method, event.params);
});
}
static get traceCategories() {
return [
'-*', // exclude default
'toplevel',
'v8.execute',
'blink.console',
'blink.user_timing',
'benchmark',
'loading',
'latencyInfo',
'devtools.timeline',
'disabled-by-default-devtools.timeline',
'disabled-by-default-devtools.timeline.frame',
'disabled-by-default-devtools.timeline.stack',
// Flipped off until bugs.chromium.org/p/v8/issues/detail?id=5820 is fixed in Stable
// 'disabled-by-default-v8.cpu_profiler',
// 'disabled-by-default-v8.cpu_profiler.hires',
'disabled-by-default-devtools.screenshot',
];
}
/**
* @return {!Promise<string>}
*/
getUserAgent() {
// FIXME: use Browser.getVersion instead
return this.evaluateAsync('navigator.userAgent');
}
/**
* @return {!Promise<null>}
*/
connect() {
return this._connection.connect();
}
disconnect() {
return this._connection.disconnect();
}
/**
* Get the browser WebSocket endpoint for devtools protocol clients like Puppeteer.
* Only works with WebSocket connection, not extension or devtools.
* @return {!Promise<string>}
*/
wsEndpoint() {
return this._connection.wsEndpoint();
}
/**
* Bind listeners for protocol events
* @param {!string} eventName
* @param {function(...args)} cb
*/
on(eventName, cb) {
if (this._eventEmitter === null) {
throw new Error('connect() must be called before attempting to listen to events.');
}
// log event listeners being bound
log.formatProtocol('listen for event =>', {method: eventName}, 'verbose');
this._eventEmitter.on(eventName, cb);
}
/**
* Bind a one-time listener for protocol events. Listener is removed once it
* has been called.
* @param {!string} eventName
* @param {function(...args)} cb
*/
once(eventName, cb) {
if (this._eventEmitter === null) {
throw new Error('connect() must be called before attempting to listen to events.');
}
// log event listeners being bound
log.formatProtocol('listen once for event =>', {method: eventName}, 'verbose');
this._eventEmitter.once(eventName, cb);
}
/**
* Unbind event listeners
* @param {!string} eventName
* @param {function(...args)} cb
*/
off(eventName, cb) {
if (this._eventEmitter === null) {
throw new Error('connect() must be called before attempting to remove an event listener.');
}
this._eventEmitter.removeListener(eventName, cb);
}
/**
* Debounce enabling or disabling domains to prevent driver users from
* stomping on each other. Maintains an internal count of the times a domain
* has been enabled. Returns false if the command would have no effect (domain
* is already enabled or disabled), or if command would interfere with another
* user of that domain (e.g. two gatherers have enabled a domain, both need to
* disable it for it to be disabled). Returns true otherwise.
* @param {string} domain
* @param {boolean} enable
* @return {boolean}
* @private
*/
_shouldToggleDomain(domain, enable) {
const enabledCount = this._domainEnabledCounts.get(domain) || 0;
const newCount = enabledCount + (enable ? 1 : -1);
this._domainEnabledCounts.set(domain, Math.max(0, newCount));
// Switching to enabled or disabled, respectively.
if ((enable && newCount === 1) || (!enable && newCount === 0)) {
log.verbose('Driver', `${domain}.${enable ? 'enable' : 'disable'}`);
return true;
} else {
if (newCount < 0) {
log.error('Driver', `Attempted to disable domain '${domain}' when already disabled.`);
}
return false;
}
}
/**
* Call protocol methods
* @param {!string} method
* @param {!Object} params
* @param {{silent: boolean}=} cmdOpts
* @return {!Promise}
*/
sendCommand(method, params, cmdOpts) {
const domainCommand = /^(\w+)\.(enable|disable)$/.exec(method);
if (domainCommand) {
const enable = domainCommand[2] === 'enable';
if (!this._shouldToggleDomain(domainCommand[1], enable)) {
return Promise.resolve();
}
}
return this._connection.sendCommand(method, params, cmdOpts);
}
/**
* Returns whether a domain is currently enabled.
* @param {string} domain
* @return {boolean}
*/
isDomainEnabled(domain) {
// Defined, non-zero elements of the domains map are enabled.
return !!this._domainEnabledCounts.get(domain);
}
/**
* Add a script to run at load time of all future page loads.
* @param {string} scriptSource
* @return {!Promise<string>} Identifier of the added script.
*/
evaluteScriptOnNewDocument(scriptSource) {
return this.sendCommand('Page.addScriptToEvaluateOnLoad', {
scriptSource,
});
}
/**
* Evaluate an expression in the context of the current page. If useIsolation is true, the expression
* will be evaluated in a content script that has access to the page's DOM but whose JavaScript state
* is completely separate.
* Returns a promise that resolves on the expression's value.
* @param {string} expression
* @param {{useIsolation: boolean}=} options
* @return {!Promise<*>}
*/
evaluateAsync(expression, options = {}) {
const contextIdPromise = options.useIsolation ?
this._getOrCreateIsolatedContextId() :
Promise.resolve(undefined);
return contextIdPromise.then(contextId => this._evaluateInContext(expression, contextId));
}
/**
* Evaluate an expression in the given execution context; an undefined contextId implies the main
* page without isolation.
* @param {string} expression
* @param {number|undefined} contextId
* @return {!Promise<*>}
*/
_evaluateInContext(expression, contextId) {
return new Promise((resolve, reject) => {
// If this gets to 60s and it hasn't been resolved, reject the Promise.
const asyncTimeout = setTimeout(
(_ => reject(new Error('The asynchronous expression exceeded the allotted time of 60s'))),
60000
);
const evaluationParams = {
// We need to explicitly wrap the raw expression for several purposes:
// 1. Ensure that the expression will be a native Promise and not a polyfill/non-Promise.
// 2. Ensure that errors in the expression are captured by the Promise.
// 3. Ensure that errors captured in the Promise are converted into plain-old JS Objects
// so that they can be serialized properly b/c JSON.stringify(new Error('foo')) === '{}'
expression: `(function wrapInNativePromise() {
const __nativePromise = window.__nativePromise || Promise;
return new __nativePromise(function (resolve) {
return __nativePromise.resolve()
.then(_ => ${expression})
.catch(${wrapRuntimeEvalErrorInBrowser.toString()})
.then(resolve);
});
}())`,
includeCommandLineAPI: true,
awaitPromise: true,
returnByValue: true,
contextId,
};
this.sendCommand('Runtime.evaluate', evaluationParams).then(result => {
clearTimeout(asyncTimeout);
const value = result.result.value;
if (result.exceptionDetails) {
// An error occurred before we could even create a Promise, should be *very* rare
reject(new Error('an unexpected driver error occurred'));
} if (value && value.__failedInBrowser) {
reject(Object.assign(new Error(), value));
} else {
resolve(value);
}
}).catch(err => {
clearTimeout(asyncTimeout);
reject(err);
});
});
}
getAppManifest() {
return this.sendCommand('Page.getAppManifest')
.then(response => {
// We're not reading `response.errors` however it may contain critical and noncritical
// errors from Blink's manifest parser:
// https://chromedevtools.github.io/debugger-protocol-viewer/tot/Page/#type-AppManifestError
if (!response.data) {
// If the data is empty, the page had no manifest.
return null;
}
return response;
});
}
getSecurityState() {
return new Promise((resolve, reject) => {
this.once('Security.securityStateChanged', data => {
this.sendCommand('Security.disable')
.then(_ => resolve(data), reject);
});
this.sendCommand('Security.enable').catch(reject);
});
}
getServiceWorkerVersions() {
return new Promise((resolve, reject) => {
const versionUpdatedListener = data => {
// find a service worker with runningStatus that looks like active
// on slow connections the serviceworker might still be installing
const activateCandidates = data.versions.filter(sw => {
return sw.status !== 'redundant';
});
const hasActiveServiceWorker = activateCandidates.find(sw => {
return sw.status === 'activated';
});
if (!activateCandidates.length || hasActiveServiceWorker) {
this.off('ServiceWorker.workerVersionUpdated', versionUpdatedListener);
this.sendCommand('ServiceWorker.disable')
.then(_ => resolve(data), reject);
}
};
this.on('ServiceWorker.workerVersionUpdated', versionUpdatedListener);
this.sendCommand('ServiceWorker.enable').catch(reject);
});
}
getServiceWorkerRegistrations() {
return new Promise((resolve, reject) => {
this.once('ServiceWorker.workerRegistrationUpdated', data => {
this.sendCommand('ServiceWorker.disable')
.then(_ => resolve(data), reject);
});
this.sendCommand('ServiceWorker.enable').catch(reject);
});
}
/**
* Rejects if any open tabs would share a service worker with the target URL.
* This includes the target tab, so navigation to something like about:blank
* should be done before calling.
* @param {!string} pageUrl
* @return {!Promise}
*/
assertNoSameOriginServiceWorkerClients(pageUrl) {
let registrations;
let versions;
return this.getServiceWorkerRegistrations().then(data => {
registrations = data.registrations;
}).then(_ => this.getServiceWorkerVersions()).then(data => {
versions = data.versions;
}).then(_ => {
const origin = new URL(pageUrl).origin;
registrations
.filter(reg => {
const swOrigin = new URL(reg.scopeURL).origin;
return origin === swOrigin;
})
.forEach(reg => {
versions.forEach(ver => {
// Ignore workers unaffiliated with this registration
if (ver.registrationId !== reg.registrationId) {
return;
}
// Throw if service worker for this origin has active controlledClients.
if (ver.controlledClients && ver.controlledClients.length > 0) {
throw new Error('You probably have multiple tabs open to the same origin.');
}
});
});
});
}
/**
* Returns a promise that resolves when the network has been idle (after DCL) for
* `networkQuietThresholdMs` ms and a method to cancel internal network listeners/timeout.
* @param {number} networkQuietThresholdMs
* @return {{promise: !Promise, cancel: function()}}
* @private
*/
_waitForNetworkIdle(networkQuietThresholdMs) {
let idleTimeout;
let cancel;
const promise = new Promise((resolve, reject) => {
const onIdle = () => {
// eslint-disable-next-line no-use-before-define
this._networkStatusMonitor.once('network-2-busy', onBusy);
idleTimeout = setTimeout(_ => {
cancel();
resolve();
}, networkQuietThresholdMs);
};
const onBusy = () => {
this._networkStatusMonitor.once('network-2-idle', onIdle);
clearTimeout(idleTimeout);
};
const domContentLoadedListener = () => {
if (this._networkStatusMonitor.is2Idle()) {
onIdle();
} else {
onBusy();
}
};
this.once('Page.domContentEventFired', domContentLoadedListener);
cancel = () => {
clearTimeout(idleTimeout);
this.off('Page.domContentEventFired', domContentLoadedListener);
this._networkStatusMonitor.removeListener('network-2-busy', onBusy);
this._networkStatusMonitor.removeListener('network-2-idle', onIdle);
};
});
return {
promise,
cancel,
};
}
/**
* Resolves when there have been no long tasks for at least waitForCPUQuiet ms.
* @param {number} waitForCPUQuiet
* @return {{promise: !Promise, cancel: function()}}
*/
_waitForCPUIdle(waitForCPUQuiet) {
if (!waitForCPUQuiet) {
return {
promise: Promise.resolve(),
cancel: () => undefined,
};
}
let lastTimeout;
let cancelled = false;
const checkForQuietExpression = `(${checkTimeSinceLastLongTask.toString()})()`;
function checkForQuiet(driver, resolve) {
if (cancelled) return;
return driver.evaluateAsync(checkForQuietExpression)
.then(timeSinceLongTask => {
if (cancelled) return;
if (typeof timeSinceLongTask === 'number' && timeSinceLongTask >= waitForCPUQuiet) {
log.verbose('Driver', `CPU has been idle for ${timeSinceLongTask} ms`);
resolve();
} else {
log.verbose('Driver', `CPU has been idle for ${timeSinceLongTask} ms`);
const timeToWait = waitForCPUQuiet - timeSinceLongTask;
lastTimeout = setTimeout(() => checkForQuiet(driver, resolve), timeToWait);
}
});
}
let cancel;
const promise = new Promise((resolve, reject) => {
checkForQuiet(this, resolve);
cancel = () => {
cancelled = true;
if (lastTimeout) clearTimeout(lastTimeout);
reject(new Error('Wait for CPU idle cancelled'));
};
});
return {
promise,
cancel,
};
}
/**
* Return a promise that resolves `pauseAfterLoadMs` after the load event fires.
* @param {number} pauseAfterLoadMs
* @return {!Promise}
*/
waitForLoadEvent(pauseAfterLoadMs = 0) {
return this._waitForLoadEvent(pauseAfterLoadMs).promise;
}
/**
* Return a promise that resolves `pauseAfterLoadMs` after the load event
* fires and a method to cancel internal listeners and timeout.
* @param {number} pauseAfterLoadMs
* @return {{promise: !Promise, cancel: function()}}
* @private
*/
_waitForLoadEvent(pauseAfterLoadMs) {
let loadListener;
let loadTimeout;
const promise = new Promise((resolve, reject) => {
loadListener = function() {
loadTimeout = setTimeout(resolve, pauseAfterLoadMs);
};
this.once('Page.loadEventFired', loadListener);
});
const cancel = () => {
this.off('Page.loadEventFired', loadListener);
clearTimeout(loadTimeout);
};
return {
promise,
cancel,
};
}
/**
* Returns a promise that resolves when:
* - All of the following conditions have been met:
* - pauseAfterLoadMs milliseconds have passed since the load event.
* - networkQuietThresholdMs milliseconds have passed since the last network request that exceeded
* 2 inflight requests (network-2-quiet has been reached).
* - cpuQuietThresholdMs have passed since the last long task after network-2-quiet.
* - maxWaitForLoadedMs milliseconds have passed.
* See https://github.com/GoogleChrome/lighthouse/issues/627 for more.
* @param {number} pauseAfterLoadMs
* @param {number} networkQuietThresholdMs
* @param {number} cpuQuietThresholdMs
* @param {number} maxWaitForLoadedMs
* @return {!Promise}
* @private
*/
_waitForFullyLoaded(pauseAfterLoadMs, networkQuietThresholdMs, cpuQuietThresholdMs,
maxWaitForLoadedMs) {
let maxTimeoutHandle;
// Listener for onload. Resolves pauseAfterLoadMs ms after load.
const waitForLoadEvent = this._waitForLoadEvent(pauseAfterLoadMs);
// Network listener. Resolves when the network has been idle for networkQuietThresholdMs.
const waitForNetworkIdle = this._waitForNetworkIdle(networkQuietThresholdMs);
// CPU listener. Resolves when the CPU has been idle for cpuQuietThresholdMs after network idle.
let waitForCPUIdle = null;
// Wait for both load promises. Resolves on cleanup function the clears load
// timeout timer.
const loadPromise = Promise.all([
waitForLoadEvent.promise,
waitForNetworkIdle.promise,
]).then(() => {
waitForCPUIdle = this._waitForCPUIdle(cpuQuietThresholdMs);
return waitForCPUIdle.promise;
}).then(() => {
return function() {
log.verbose('Driver', 'loadEventFired and network considered idle');
clearTimeout(maxTimeoutHandle);
};
});
// Last resort timeout. Resolves maxWaitForLoadedMs ms from now on
// cleanup function that removes loadEvent and network idle listeners.
const maxTimeoutPromise = new Promise((resolve, reject) => {
maxTimeoutHandle = setTimeout(resolve, maxWaitForLoadedMs);
}).then(_ => {
return function() {
log.warn('Driver', 'Timed out waiting for page load. Moving on...');
waitForLoadEvent.cancel();
waitForNetworkIdle.cancel();
waitForCPUIdle && waitForCPUIdle.cancel();
};
});
// Wait for load or timeout and run the cleanup function the winner returns.
return Promise.race([
loadPromise,
maxTimeoutPromise,
]).then(cleanup => cleanup());
}
/**
* Set up listener for network quiet events and URL redirects. Passed in URL
* will be monitored for redirects, with the final loaded URL passed back in
* _endNetworkStatusMonitoring.
* @param {string} startingUrl
* @return {!Promise}
* @private
*/
_beginNetworkStatusMonitoring(startingUrl) {
this._networkStatusMonitor = new NetworkRecorder([]);
// Update startingUrl if it's ever redirected.
this._monitoredUrl = startingUrl;
this._networkStatusMonitor.on('requestloaded', redirectRequest => {
// Ignore if this is not a redirected request.
if (!redirectRequest.redirectSource) {
return;
}
const earlierRequest = redirectRequest.redirectSource;
if (earlierRequest.url === this._monitoredUrl) {
this._monitoredUrl = redirectRequest.url;
}
});
return this.sendCommand('Network.enable');
}
/**
* End network status listening. Returns the final, possibly redirected,
* loaded URL starting with the one passed into _endNetworkStatusMonitoring.
* @return {string}
* @private
*/
_endNetworkStatusMonitoring() {
this._networkStatusMonitor = null;
const finalUrl = this._monitoredUrl;
this._monitoredUrl = null;
return finalUrl;
}
/**
* Returns the cached isolated execution context ID or creates a new execution context for the main
* frame. The cached execution context is cleared on every gotoURL invocation, so a new one will
* always be created on the first call on a new page.
* @return {!Promise<number>}
*/
_getOrCreateIsolatedContextId() {
if (typeof this._isolatedExecutionContextId === 'number') {
return Promise.resolve(this._isolatedExecutionContextId);
}
return this.sendCommand('Page.getResourceTree')
.then(data => {
const mainFrameId = data.frameTree.frame.id;
return this.sendCommand('Page.createIsolatedWorld', {
frameId: mainFrameId,
worldName: 'lighthouse_isolated_context',
});
})
.then(data => this._isolatedExecutionContextId = data.executionContextId);
}
_clearIsolatedContextId() {
this._isolatedExecutionContextId = undefined;
}
/**
* Navigate to the given URL. Direct use of this method isn't advised: if
* the current page is already at the given URL, navigation will not occur and
* so the returned promise will only resolve after the MAX_WAIT_FOR_FULLY_LOADED
* timeout. See https://github.com/GoogleChrome/lighthouse/pull/185 for one
* possible workaround.
* Resolves on the url of the loaded page, taking into account any redirects.
* @param {string} url
* @param {!Object} options
* @return {!Promise<string>}
*/
gotoURL(url, options = {}) {
const waitForLoad = options.waitForLoad || false;
const disableJS = options.disableJavaScript || false;
let pauseAfterLoadMs = options.config && options.config.pauseAfterLoadMs;
let networkQuietThresholdMs = options.config && options.config.networkQuietThresholdMs;
let cpuQuietThresholdMs = options.config && options.config.cpuQuietThresholdMs;
let maxWaitMs = options.flags && options.flags.maxWaitForLoad;
/* eslint-disable max-len */
if (typeof pauseAfterLoadMs !== 'number') pauseAfterLoadMs = DEFAULT_PAUSE_AFTER_LOAD;
if (typeof networkQuietThresholdMs !== 'number') networkQuietThresholdMs = DEFAULT_NETWORK_QUIET_THRESHOLD;
if (typeof cpuQuietThresholdMs !== 'number') cpuQuietThresholdMs = DEFAULT_CPU_QUIET_THRESHOLD;
if (typeof maxWaitMs !== 'number') maxWaitMs = Driver.MAX_WAIT_FOR_FULLY_LOADED;
/* eslint-enable max-len */
return this._beginNetworkStatusMonitoring(url)
.then(_ => this._clearIsolatedContextId())
.then(_ => {
// These can 'race' and that's OK.
// We don't want to wait for Page.navigate's resolution, as it can now
// happen _after_ onload: https://crbug.com/768961
this.sendCommand('Page.enable');
this.sendCommand('Emulation.setScriptExecutionDisabled', {value: disableJS});
this.sendCommand('Page.navigate', {url});
})
.then(_ => waitForLoad && this._waitForFullyLoaded(pauseAfterLoadMs,
networkQuietThresholdMs, cpuQuietThresholdMs, maxWaitMs))
.then(_ => this._endNetworkStatusMonitoring());
}
/**
* @param {string} objectId Object ID for the resolved DOM node
* @param {string} propName Name of the property
* @return {!Promise<string>} The property value, or null, if property not found
*/
getObjectProperty(objectId, propName) {
return new Promise((resolve, reject) => {
this.sendCommand('Runtime.getProperties', {
objectId,
accessorPropertiesOnly: true,
generatePreview: false,
ownProperties: false,
})
.then(properties => {
const propertyForName = properties.result
.find(property => property.name === propName);
if (propertyForName && propertyForName.value) {
resolve(propertyForName.value.value);
} else {
resolve(null);
}
}).catch(reject);
});
}
/**
* Return the body of the response with the given ID.
* @param {string} requestId
* @return {string}
*/
getRequestContent(requestId) {
return this.sendCommand('Network.getResponseBody', {
requestId,
// Ignoring result.base64Encoded, which indicates if body is already encoded
}).then(result => result.body);
}
/**
* @param {string} name The name of API whose permission you wish to query
* @return {!Promise<string>} The state of permissions, resolved in a promise.
* See https://developer.mozilla.org/en-US/docs/Web/API/Permissions/query.
*/
queryPermissionState(name) {
const expressionToEval = `
navigator.permissions.query({name: '${name}'}).then(result => {
return result.state;
})
`;
return this.evaluateAsync(expressionToEval);
}
/**
* @param {string} selector Selector to find in the DOM
* @return {!Promise<Element>} The found element, or null, resolved in a promise
*/
querySelector(selector) {
return this.sendCommand('DOM.getDocument')
.then(result => result.root.nodeId)
.then(nodeId => this.sendCommand('DOM.querySelector', {
nodeId,
selector,
}))
.then(element => {
if (element.nodeId === 0) {
return null;
}
return new Element(element, this);
});
}
/**
* @param {string} selector Selector to find in the DOM
* @return {!Promise<!Array<!Element>>} The found elements, or [], resolved in a promise
*/
querySelectorAll(selector) {
return this.sendCommand('DOM.getDocument')
.then(result => result.root.nodeId)
.then(nodeId => this.sendCommand('DOM.querySelectorAll', {
nodeId,
selector,
}))
.then(nodeList => {
const elementList = [];
nodeList.nodeIds.forEach(nodeId => {
if (nodeId !== 0) {
elementList.push(new Element({nodeId}, this));
}
});
return elementList;
});
}
/**
* Returns the flattened list of all DOM elements within the document.
* @param {boolean=} pierce Whether to pierce through shadow trees and iframes.
* True by default.
* @return {!Promise<!Array<!Element>>} The found elements, or [], resolved in a promise
*/
getElementsInDocument(pierce = true) {
return this.getNodesInDocument(pierce)
.then(nodes => nodes
.filter(node => node.nodeType === 1)
.map(node => new Element({nodeId: node.nodeId}, this))
);
}
/**
* Returns the flattened list of all DOM nodes within the document.
* @param {boolean=} pierce Whether to pierce through shadow trees and iframes.
* True by default.
* @return {!Promise<!Array<!Node>>} The found nodes, or [], resolved in a promise
*/
getNodesInDocument(pierce = true) {
return this.sendCommand('DOM.getFlattenedDocument', {depth: -1, pierce})
.then(result => result.nodes ? result.nodes : []);
}
/**
* @param {{additionalTraceCategories: string=}=} flags
*/
beginTrace(flags) {
const additionalCategories = (flags && flags.additionalTraceCategories &&
flags.additionalTraceCategories.split(',')) || [];
const traceCategories = this._traceCategories.concat(additionalCategories);
const tracingOpts = {
categories: _uniq(traceCategories).join(','),
transferMode: 'ReturnAsStream',
options: 'sampling-frequency=10000', // 1000 is default and too slow.
};
// Check any domains that could interfere with or add overhead to the trace.
if (this.isDomainEnabled('Debugger')) {
throw new Error('Debugger domain enabled when starting trace');
}
if (this.isDomainEnabled('CSS')) {
throw new Error('CSS domain enabled when starting trace');
}
if (this.isDomainEnabled('DOM')) {
throw new Error('DOM domain enabled when starting trace');
}
// Enable Page domain to wait for Page.loadEventFired
return this.sendCommand('Page.enable')
// ensure tracing is stopped before we can start
// see https://github.com/GoogleChrome/lighthouse/issues/1091
.then(_ => this.endTraceIfStarted())
.then(_ => this.sendCommand('Tracing.start', tracingOpts));
}
endTraceIfStarted() {
return new Promise((resolve) => {
const traceCallback = () => resolve();
this.once('Tracing.tracingComplete', traceCallback);
return this.sendCommand('Tracing.end', undefined, {silent: true}).catch(() => {
this.off('Tracing.tracingComplete', traceCallback);
traceCallback();
});
});
}
endTrace() {
return new Promise((resolve, reject) => {
// When the tracing has ended this will fire with a stream handle.
this.once('Tracing.tracingComplete', streamHandle => {
this._readTraceFromStream(streamHandle)
.then(traceContents => resolve(traceContents), reject);
});
// Issue the command to stop tracing.
return this.sendCommand('Tracing.end').catch(reject);
});
}
_readTraceFromStream(streamHandle) {
return new Promise((resolve, reject) => {
let isEOF = false;
const parser = new TraceParser();
const readArguments = {
handle: streamHandle.stream,
};
const onChunkRead = response => {
if (isEOF) {
return;
}
parser.parseChunk(response.data);
if (response.eof) {
isEOF = true;
return resolve(parser.getTrace());
}
return this.sendCommand('IO.read', readArguments).then(onChunkRead);
};
this.sendCommand('IO.read', readArguments).then(onChunkRead).catch(reject);
});
}
/**
* Begin recording devtools protocol messages.
*/
beginDevtoolsLog() {
this._devtoolsLog.reset();
this._devtoolsLog.beginRecording();
}
/**
* Stop recording to devtoolsLog and return log contents.
* @return {!Array<{method: string, params: (!Object<string, *>|undefined)}>}
*/
endDevtoolsLog() {
this._devtoolsLog.endRecording();
return this._devtoolsLog.messages;
}
enableRuntimeEvents() {
return this.sendCommand('Runtime.enable');
}
beginEmulation(flags) {
return Promise.resolve().then(_ => {
if (!flags.disableDeviceEmulation) return emulation.enableNexus5X(this);
}).then(_ => this.setThrottling(flags, {useThrottling: true}));
}
setThrottling(flags, passConfig) {
const throttleCpu = passConfig.useThrottling && !flags.disableCpuThrottling;
const throttleNetwork = passConfig.useThrottling && !flags.disableNetworkThrottling;
const cpuPromise = throttleCpu ?
emulation.enableCPUThrottling(this) :
emulation.disableCPUThrottling(this);
const networkPromise = throttleNetwork ?
emulation.enableNetworkThrottling(this) :
emulation.disableNetworkThrottling(this);
return Promise.all([cpuPromise, networkPromise]);
}
/**
* Emulate internet disconnection.
* @return {!Promise}
*/
goOffline() {
return this.sendCommand('Network.enable')
.then(_ => emulation.goOffline(this))
.then(_ => this.online = false);
}
/**
* Enable internet connection, using emulated mobile settings if
* `options.flags.disableNetworkThrottling` is false.
* @param {!Object} options
* @return {!Promise}
*/
goOnline(options) {
return this.setThrottling(options.flags, options.config)
.then(_ => this.online = true);
}
cleanBrowserCaches() {
// Wipe entire disk cache
return this.sendCommand('Network.clearBrowserCache')
// Toggle 'Disable Cache' to evict the memory cache
.then(_ => this.sendCommand('Network.setCacheDisabled', {cacheDisabled: true}))
.then(_ => this.sendCommand('Network.setCacheDisabled', {cacheDisabled: false}));
}
/**
* @param {!Object} headers key/value pairs of HTTP Headers.
* @return {!Promise}
*/
setExtraHTTPHeaders(headers) {
if (headers) {
return this.sendCommand('Network.setExtraHTTPHeaders', {
headers,
});
}
return Promise.resolve({});
}
clearDataForOrigin(url) {
const origin = new URL(url).origin;
// Clear all types of storage except cookies, so the user isn't logged out.
// https://chromedevtools.github.io/debugger-protocol-viewer/tot/Storage/#type-StorageType
const typesToClear = [
'appcache',