Skip to content
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

new_audit: add no-unload-listeners audit #11085

Merged
merged 7 commits into from
Jul 21, 2020
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
11 changes: 11 additions & 0 deletions lighthouse-cli/test/cli/__snapshots__/index-test.js.snap
Original file line number Diff line number Diff line change
Expand Up @@ -159,6 +159,9 @@ Object {
Object {
"path": "long-tasks",
},
Object {
"path": "no-unload-listeners",
},
Object {
"path": "manual/pwa-cross-browser",
},
Expand Down Expand Up @@ -747,6 +750,11 @@ Object {
"id": "charset",
"weight": 1,
},
Object {
"group": "best-practices-general",
"id": "no-unload-listeners",
"weight": 1,
},
Object {
"group": "best-practices-general",
"id": "appcache-manifest",
Expand Down Expand Up @@ -1323,6 +1331,9 @@ Object {
Object {
"path": "main-document-content",
},
Object {
"path": "global-listeners",
},
Object {
"path": "dobetterweb/appcache",
},
Expand Down
7 changes: 7 additions & 0 deletions lighthouse-cli/test/fixtures/dobetterweb/dbw_tester.html
Original file line number Diff line number Diff line change
Expand Up @@ -383,6 +383,12 @@ <h2>Do better web tester page</h2>
document.body.appendChild(img); // PASS
}

function noUnloadListenersTest() {
window.addEventListener('unload', () => {
console.log('unload on unload');
});
}

// Figure out which tests to fun.
const params = new URLSearchParams(location.search);
if (location.search === '') {
Expand All @@ -398,6 +404,7 @@ <h2>Do better web tester page</h2>
deprecationsTest();
passwordInputsCanBePastedIntoTest();
isOnHttps();
noUnloadListenersTest();
} else {
if (params.has('documentWrite')) {
documentWriteTest();
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -197,6 +197,12 @@ const expectations = [
},
},
],
GlobalListeners: [{
type: 'unload',
scriptId: /^\d+$/,
lineNumber: '>300',
columnNumber: '>30',
}],
},
lhr: {
requestedUrl: 'http://localhost:10200/dobetterweb/dbw_tester.html',
Expand Down Expand Up @@ -413,6 +419,20 @@ const expectations = [
],
},
},
'no-unload-listeners': {
score: 0,
details: {
items: [{
source: {
type: 'source-location',
url: 'http://localhost:10200/dobetterweb/dbw_tester.html',
urlProvider: 'network',
line: '>300',
column: '>30',
},
}],
},
},
},
},
},
Expand Down
94 changes: 94 additions & 0 deletions lighthouse-core/audits/no-unload-listeners.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,94 @@
/**
* @license Copyright 2020 The Lighthouse Authors. 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.
*/
'use strict';

const Audit = require('./audit.js');
const i18n = require('./../lib/i18n/i18n.js');

const UIStrings = {
/** Descriptive title of a Lighthouse audit that checks if a web page has 'unload' event listeners and finds none. */
title: 'Avoids `unload` event listeners',
/** Descriptive title of a Lighthouse audit that checks if a web page has 'unload' event listeners and finds that it is using them. */
failureTitle: 'Registers an `unload` listener',
/** Description of a Lighthouse audit that tells the user why pages should not use the 'unload' event. This is displayed after a user expands the section to see more. 'Learn More' becomes link text to additional documentation. */
description: 'The `unload` event does not fire reliably and listening for it can prevent browser optimizations like the Back-Forward Cache. Consider using the `pagehide` or `visibilitychange` events instead. [Learn More](https://developers.google.com/web/updates/2018/07/page-lifecycle-api#the-unload-event)',
};

const str_ = i18n.createMessageInstanceIdFn(__filename, UIStrings);

class NoUnloadListeners extends Audit {
/**
* @return {LH.Audit.Meta}
*/
static get meta() {
return {
id: 'no-unload-listeners',
title: str_(UIStrings.title),
failureTitle: str_(UIStrings.failureTitle),
description: str_(UIStrings.description),
requiredArtifacts: ['GlobalListeners', 'JsUsage'],
};
}

/**
* @param {LH.Artifacts} artifacts
* @return {LH.Audit.Product}
*/
static audit(artifacts) {
const unloadListeners = artifacts.GlobalListeners.filter(l => l.type === 'unload');
if (!unloadListeners.length) {
return {
score: 1,
};
}

/** @type {LH.Audit.Details.Table['headings']} */
const headings = [
{key: 'source', itemType: 'source-location', text: str_(i18n.UIStrings.columnURL)},
];

// Look up scriptId to script URL via the JsUsage artifact.
/** @type {Array<[string, string]>} */
const scriptIdToUrlEntries = Object.values(artifacts.JsUsage)
.reduce((acc, usage) => acc.concat(usage), []) // single-level arr.flat().
.map(usage => [usage.scriptId, usage.url]);
const scriptIdToUrl = new Map(scriptIdToUrlEntries);

/** @type {Array<{source: LH.Audit.Details.ItemValue}>} */
const tableItems = unloadListeners.map(listener => {
const url = scriptIdToUrl.get(listener.scriptId);

// If we can't find a url, still show something so the user can manually
// look for where an `unload` handler is being created.
if (!url) {
return {
source: {
type: 'url',
value: '(unknown)',
},
};
}

return {
source: {
type: 'source-location',
url,
urlProvider: 'network',
line: listener.lineNumber,
column: listener.columnNumber,
},
};
});

return {
score: 0,
details: Audit.makeTableDetails(headings, tableItems),
};
}
}

module.exports = NoUnloadListeners;
module.exports.UIStrings = UIStrings;
3 changes: 3 additions & 0 deletions lighthouse-core/config/default-config.js
Original file line number Diff line number Diff line change
Expand Up @@ -147,6 +147,7 @@ const defaultConfig = {
'script-elements',
'iframe-elements',
'main-document-content',
'global-listeners',
'dobetterweb/appcache',
'dobetterweb/doctype',
'dobetterweb/domstats',
Expand Down Expand Up @@ -236,6 +237,7 @@ const defaultConfig = {
'largest-contentful-paint-element',
'layout-shift-elements',
'long-tasks',
'no-unload-listeners',
'manual/pwa-cross-browser',
'manual/pwa-page-transitions',
'manual/pwa-each-page-has-url',
Expand Down Expand Up @@ -556,6 +558,7 @@ const defaultConfig = {
{id: 'doctype', weight: 1, group: 'best-practices-browser-compat'},
{id: 'charset', weight: 1, group: 'best-practices-browser-compat'},
// General Group
{id: 'no-unload-listeners', weight: 1, group: 'best-practices-general'},
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

feels like it could be a diagnostic too, any particular decision insights behind best practices we can leave for future git blame archeologists? :)

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

feels like it could be a diagnostic too, any particular decision insights behind best practices we can leave for future git blame archeologists? :)

I guess it kind of falls in with uses-long-cache-ttl as something diagnosing performance, just not the performance of any of the metrics just measured (since a Lighthouse run isn't (usually) with a warm cache or on a hit of the back button). I guess I could see the argument that it's still worthwhile to have there, but I chose this as the uncontroversial spot to put it. I don't feel strongly :)

{id: 'appcache-manifest', weight: 1, group: 'best-practices-general'},
{id: 'js-libraries', weight: 0, group: 'best-practices-general'},
{id: 'deprecations', weight: 1, group: 'best-practices-general'},
Expand Down
60 changes: 60 additions & 0 deletions lighthouse-core/gather/gatherers/global-listeners.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,60 @@
/**
* @license Copyright 2020 The Lighthouse Authors. 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.
*/
'use strict';

/**
* @fileoverview
* A gatherer to collect information about the event listeners registered on the
* global object. For now, the scope is narrowed to events that occur on and
* around page unload, but this can be expanded in the future.
*/

const Gatherer = require('./gatherer.js');

class GlobalListeners extends Gatherer {
brendankenny marked this conversation as resolved.
Show resolved Hide resolved
/**
* @param {LH.Crdp.DOMDebugger.EventListener} listener
* @return {listener is {type: 'pagehide'|'unload'|'visibilitychange'} & LH.Crdp.DOMDebugger.EventListener}
*/
static _filterForAllowlistedTypes(listener) {
return listener.type === 'pagehide' ||
listener.type === 'unload' ||
listener.type === 'visibilitychange';
}

/**
* @param {LH.Gatherer.PassContext} passContext
* @return {Promise<LH.Artifacts['GlobalListeners']>}
*/
async afterPass(passContext) {
const driver = passContext.driver;

// Get a RemoteObject handle to `window`.
const {result: {objectId}} = await driver.sendCommand('Runtime.evaluate', {
expression: 'window',
returnByValue: false,
});
if (!objectId) {
throw new Error('Error fetching information about the global object');
}

// And get all its listeners of interest.
const {listeners} = await driver.sendCommand('DOMDebugger.getEventListeners', {objectId});
return listeners
.filter(GlobalListeners._filterForAllowlistedTypes)
.map(listener => {
const {type, scriptId, lineNumber, columnNumber} = listener;
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I'm just noticing this is already back in node-land so serialization isn't the reason for reexposing, just trying to limit what we return?

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

just trying to limit what we return?

yeah

return {
type,
scriptId,
lineNumber,
columnNumber,
};
});
}
}

module.exports = GlobalListeners;
9 changes: 9 additions & 0 deletions lighthouse-core/lib/i18n/locales/en-US.json
Original file line number Diff line number Diff line change
Expand Up @@ -959,6 +959,15 @@
"lighthouse-core/audits/network-server-latency.js | title": {
"message": "Server Backend Latencies"
},
"lighthouse-core/audits/no-unload-listeners.js | description": {
"message": "The `unload` event does not fire reliably and listening for it can prevent browser optimizations like the Back-Forward Cache. Consider using the `pagehide` or `visibilitychange` events instead. [Learn More](https://developers.google.com/web/updates/2018/07/page-lifecycle-api#the-unload-event)"
},
"lighthouse-core/audits/no-unload-listeners.js | failureTitle": {
"message": "Registers an `unload` listener"
},
"lighthouse-core/audits/no-unload-listeners.js | title": {
"message": "Avoids `unload` event listeners"
},
"lighthouse-core/audits/offline-start-url.js | description": {
"message": "A service worker enables your web app to be reliable in unpredictable network conditions. [Learn more](https://web.dev/offline-start-url/)."
},
Expand Down
9 changes: 9 additions & 0 deletions lighthouse-core/lib/i18n/locales/en-XL.json
Original file line number Diff line number Diff line change
Expand Up @@ -959,6 +959,15 @@
"lighthouse-core/audits/network-server-latency.js | title": {
"message": "Ŝér̂v́êŕ B̂áĉḱêńd̂ Ĺât́êńĉíêś"
},
"lighthouse-core/audits/no-unload-listeners.js | description": {
"message": "T̂h́ê `unload` év̂én̂t́ d̂óêś n̂ót̂ f́îŕê ŕêĺîáb̂ĺŷ án̂d́ l̂íŝt́êńîńĝ f́ôŕ ît́ ĉán̂ ṕr̂év̂én̂t́ b̂ŕôẃŝér̂ óp̂t́îḿîźât́îón̂ś l̂ík̂é t̂h́ê B́âćk̂-F́ôŕŵár̂d́ Ĉáĉh́ê. Ćôńŝíd̂ér̂ úŝín̂ǵ t̂h́ê `pagehide` ór̂ `visibilitychange` év̂én̂t́ŝ ín̂śt̂éâd́. [L̂éâŕn̂ Ḿôŕê](https://developers.google.com/web/updates/2018/07/page-lifecycle-api#the-unload-event)"
},
"lighthouse-core/audits/no-unload-listeners.js | failureTitle": {
"message": "R̂éĝíŝt́êŕŝ án̂ `unload` ĺîśt̂én̂ér̂"
},
"lighthouse-core/audits/no-unload-listeners.js | title": {
"message": "Âv́ôíd̂ś `unload` êv́êńt̂ ĺîśt̂én̂ér̂ś"
},
"lighthouse-core/audits/offline-start-url.js | description": {
"message": "Â śêŕv̂íĉé ŵór̂ḱêŕ êńâb́l̂éŝ ýôúr̂ ẃêb́ âṕp̂ t́ô b́ê ŕêĺîáb̂ĺê ín̂ ún̂ṕr̂éd̂íĉt́âb́l̂é n̂ét̂ẃôŕk̂ ćôńd̂ít̂íôńŝ. [Ĺêár̂ń m̂ór̂é](https://web.dev/offline-start-url/)."
},
Expand Down
77 changes: 77 additions & 0 deletions lighthouse-core/test/audits/no-unload-listeners-test.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,77 @@
/**
* @license Copyright 2020 The Lighthouse Authors. 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.
*/
'use strict';

const NoUnloadListeners = require('../../audits/no-unload-listeners.js');

/* eslint-env jest */

const testJsUsage = {
'https://example.com/1.js': [
{scriptId: '12', url: 'https://example.com/1.js', functions: []},
{scriptId: '13', url: 'https://example.com/1.js', functions: []},
{scriptId: '16', url: 'https://example.com/1.js', functions: []},
{scriptId: '17', url: 'https://example.com/1.js', functions: []},
],
'https://example.com/2.js': [
{scriptId: '22', url: 'https://example.com/2.js', functions: []},
{scriptId: '23', url: 'https://example.com/2.js', functions: []},
{scriptId: '26', url: 'https://example.com/2.js', functions: []},
{scriptId: '27', url: 'https://example.com/2.js', functions: []},
],
};

describe('No Unload Listeners', () => {
it('passes when there were no listeners', () => {
const artifacts = {JsUsage: testJsUsage, GlobalListeners: []};
const result = NoUnloadListeners.audit(artifacts);
expect(result).toEqual({score: 1});
});

it('passes when there were no `unload` listeners', () => {
const GlobalListeners = [{
type: 'DOMContentLoaded', scriptId: '12', lineNumber: 5, columnNumber: 0,
}];
const artifacts = {JsUsage: testJsUsage, GlobalListeners};
const result = NoUnloadListeners.audit(artifacts);
expect(result).toEqual({score: 1});
});

it('fails when there are unload listeners and matches them to script locations', () => {
const GlobalListeners = [
{type: 'unload', scriptId: '16', lineNumber: 10, columnNumber: 30},
{type: 'unload', scriptId: '23', lineNumber: 0, columnNumber: 0},
];
const artifacts = {JsUsage: testJsUsage, GlobalListeners};
const result = NoUnloadListeners.audit(artifacts);
expect(result.score).toEqual(0);
expect(result.details.items).toMatchObject([
{
source: {type: 'source-location', url: 'https://example.com/1.js', urlProvider: 'network', line: 10, column: 30},
}, {
source: {type: 'source-location', url: 'https://example.com/2.js', urlProvider: 'network', line: 0, column: 0},
},
]);
});

it('fails when there are unload listeners and has a fallback if script URL is not found', () => {
const GlobalListeners = [
{type: 'DOMContentLoaded', scriptId: '12', lineNumber: 5, columnNumber: 0},
{type: 'unload', scriptId: 'notascriptid', lineNumber: 10, columnNumber: 30},
{type: 'unload', scriptId: '22', lineNumber: 1, columnNumber: 100},
];
const artifacts = {JsUsage: testJsUsage, GlobalListeners};
const result = NoUnloadListeners.audit(artifacts);
expect(result.score).toEqual(0);
expect(result.details.items).toMatchObject([
{
source: {type: 'url', value: '(unknown)'},
}, {
source: {type: 'source-location', url: 'https://example.com/2.js', urlProvider: 'network', line: 1, column: 100},
},
]);
});
});