-
Notifications
You must be signed in to change notification settings - Fork 9.4k
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
core(driver): move evaluateOnNewDocument to executionContext #12381
Merged
Merged
Changes from 4 commits
Commits
Show all changes
10 commits
Select commit
Hold shift + click to select a range
308035a
core(driver): move evaluateOnNewDocument to executionContext
patrickhulce 8daccd5
add serialize argument test with undefined
patrickhulce cbaddd3
update evaluate too
patrickhulce 8010055
tamper-proof performance.now
patrickhulce 334e37b
fix wrap document thing
patrickhulce 02f0def
feedback
patrickhulce 806da6f
Update lighthouse-core/gather/driver/execution-context.js
patrickhulce 29c93b8
Merge branch 'master' into fr_refactor_cache_natives
patrickhulce 2de1116
Merge branch 'fr_refactor_cache_natives' of github.com:GoogleChrome/l…
patrickhulce 55ac3b0
add c8 annotations to injected script
patrickhulce File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
|
@@ -5,6 +5,8 @@ | |
*/ | ||
'use strict'; | ||
|
||
/* global window */ | ||
|
||
const pageFunctions = require('../../lib/page-functions.js'); | ||
|
||
class ExecutionContext { | ||
|
@@ -83,11 +85,10 @@ class ExecutionContext { | |
// 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 = globalThis.__nativePromise || Promise; | ||
const URL = globalThis.__nativeURL || globalThis.URL; | ||
${ExecutionContext._cachedNativesPreamble}; | ||
globalThis.__lighthouseExecutionContextId = ${contextId}; | ||
return new __nativePromise(function (resolve) { | ||
return __nativePromise.resolve() | ||
return new Promise(function (resolve) { | ||
return Promise.resolve() | ||
.then(_ => ${expression}) | ||
.catch(${pageFunctions.wrapRuntimeEvalErrorInBrowserString}) | ||
.then(resolve); | ||
|
@@ -164,14 +165,79 @@ class ExecutionContext { | |
* @return {FlattenedPromise<R>} | ||
*/ | ||
evaluate(mainFn, options) { | ||
const argsSerialized = options.args.map(arg => JSON.stringify(arg)).join(','); | ||
const argsSerialized = ExecutionContext.serializeArguments(options.args); | ||
const depsSerialized = options.deps ? options.deps.join('\n') : ''; | ||
const expression = `(() => { | ||
${depsSerialized} | ||
return (${mainFn})(${argsSerialized}); | ||
})()`; | ||
return this.evaluateAsync(expression, options); | ||
} | ||
|
||
/** | ||
* Evaluate a function on every new frame from now on. | ||
* @template {any[]} T | ||
patrickhulce marked this conversation as resolved.
Show resolved
Hide resolved
|
||
* @param {((...args: T) => void)} mainFn The main function to call. | ||
* @param {{args: T, deps?: Array<Function|string>}} options `args` should | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. yayyy |
||
* match the args of `mainFn`, and can be any serializable value. `deps` are functions that must be | ||
* defined for `mainFn` to work. | ||
* @return {Promise<void>} | ||
*/ | ||
async evaluateOnNewDocument(mainFn, options) { | ||
const argsSerialized = ExecutionContext.serializeArguments(options.args); | ||
const depsSerialized = options.deps ? options.deps.join('\n') : ''; | ||
|
||
const expression = ` | ||
${ExecutionContext._cachedNativesPreamble}; | ||
${depsSerialized}; | ||
(${mainFn})(${argsSerialized}); | ||
`; | ||
|
||
await this._session.sendCommand('Page.addScriptToEvaluateOnNewDocument', {source: expression}); | ||
} | ||
|
||
/** | ||
* Cache native functions/objects inside window so we are sure polyfills do not overwrite the | ||
* native implementations when the page loads. | ||
* @return {Promise<void>} | ||
*/ | ||
async cacheNativesOnNewDocument() { | ||
await this.evaluateOnNewDocument(() => { | ||
window.__nativePromise = window.Promise; | ||
window.__nativeURL = window.URL; | ||
window.__nativePerformance = window.performance; | ||
window.__ElementMatches = window.Element.prototype.matches; | ||
// Ensure the native `performance.now` is not overwritable. | ||
const performance = window.performance; | ||
const performanceNow = window.performance.now; | ||
Object.defineProperty(performance, 'now', { | ||
value: () => performanceNow.call(performance), | ||
writable: false, | ||
}); | ||
}, {args: []}); | ||
} | ||
|
||
/** | ||
* Prefix every script evaluation with a shadowing of common globals that tend to be ponyfilled | ||
* incorrectly by many sites. This allows functions to still refer to `Promise` instead of | ||
* Lighthouse-specific backups like `__nativePromise`. | ||
patrickhulce marked this conversation as resolved.
Show resolved
Hide resolved
|
||
*/ | ||
static get _cachedNativesPreamble() { | ||
return [ | ||
'const Promise = globalThis.__nativePromise || globalThis.Promise', | ||
'const URL = globalThis.__nativeURL || globalThis.URL', | ||
'const performance = globalThis.__nativePerformance || globalThis.performance', | ||
].join(';\n'); | ||
} | ||
patrickhulce marked this conversation as resolved.
Show resolved
Hide resolved
|
||
|
||
/** | ||
* Serializes an array of arguments for use in an `eval` string across the protocol. | ||
* @param {any[]} args | ||
patrickhulce marked this conversation as resolved.
Show resolved
Hide resolved
|
||
* @return {string} | ||
*/ | ||
static serializeArguments(args) { | ||
return args.map(arg => arg === undefined ? 'undefined' : JSON.stringify(arg)).join(','); | ||
} | ||
} | ||
|
||
module.exports = ExecutionContext; |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
|
@@ -393,11 +393,11 @@ declare global { | |
|
||
interface Window { | ||
// Cached native functions/objects for use in case the page overwrites them. | ||
// See: `driver.cacheNatives`. | ||
// See: `executionContext.cacheNativesOnNewDocument`. | ||
__nativePromise: PromiseConstructor; | ||
__nativeURL: URL; | ||
__nativePerformance: Performance; | ||
__nativeURL: typeof URL; | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. this was typed incorrectly, but we never use it :) |
||
__ElementMatches: Element['matches']; | ||
__perfNow: Performance['now']; | ||
|
||
/** Used for monitoring long tasks in the test page. */ | ||
____lastLongTask?: number; | ||
|
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
very nice!