forked from GoogleChrome/lighthouse
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathextension-entry.js
235 lines (203 loc) · 7.61 KB
/
extension-entry.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
/**
* @license Copyright 2018 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.
*/
'use strict';
const lighthouse = require('../../../lighthouse-core/index');
const Config = require('../../../lighthouse-core/config/config');
const defaultConfig = require('../../../lighthouse-core/config/default-config.js');
const i18n = require('../../../lighthouse-core/lib/i18n/i18n.js');
const ExtensionProtocol = require('../../../lighthouse-core/gather/connections/extension');
const log = require('lighthouse-logger');
/** @typedef {import('../../../lighthouse-core/gather/connections/connection.js')} Connection */
const STORAGE_KEY = 'lighthouse_audits';
const SETTINGS_KEY = 'lighthouse_settings';
let lighthouseIsRunning = false;
/** @type {?[string, string, string]} */
let latestStatusLog = null;
/**
* Returns list of top-level categories from the default config.
* @return {Array<{title: string, id: string}>}
*/
function getDefaultCategories() {
const categories = Config.getCategories(defaultConfig);
categories.forEach(cat => cat.title = i18n.getFormatted(cat.title, 'en-US'));
return categories;
}
/**
* Return a version of the default config, filtered to only run the specified
* categories.
* @param {Array<string>} categoryIDs
* @return {LH.Config.Json}
*/
function getDefaultConfigForCategories(categoryIDs) {
return {
extends: 'lighthouse:default',
settings: {
onlyCategories: categoryIDs,
},
};
}
/**
* Sets the extension badge text.
* @param {string=} optUrl If present, sets the badge text to "Testing <url>".
* Otherwise, restore the default badge text.
*/
function updateBadgeUI(optUrl) {
lighthouseIsRunning = !!optUrl;
if ('chrome' in window && chrome.runtime) {
const manifest = chrome.runtime.getManifest();
if (!manifest.browser_action || !manifest.browser_action.default_icon) {
return;
}
let title = manifest.browser_action.default_title || '';
let path = manifest.browser_action.default_icon[38];
if (lighthouseIsRunning) {
title = `Testing ${optUrl}`;
path = 'images/lh_logo_icon_light.png';
}
chrome.browserAction.setTitle({title});
chrome.browserAction.setIcon({path});
}
}
/**
* @param {LH.Flags} flags Lighthouse flags.
* @param {Array<string>} categoryIDs Name values of categories to include.
* @return {Promise<LH.RunnerResult|void>}
*/
async function runLighthouseInExtension(flags, categoryIDs) {
// Default to 'info' logging level.
flags.logLevel = flags.logLevel || 'info';
flags.output = 'html';
const connection = new ExtensionProtocol();
const url = await connection.getCurrentTabURL();
const config = getDefaultConfigForCategories(categoryIDs);
updateBadgeUI(url);
let runnerResult;
try {
runnerResult = await lighthouse(url, flags, config, connection);
} finally {
updateBadgeUI();
}
if (!runnerResult) {
// For now, should always be a runnerResult as the extension can't do `gatherMode`
throw new Error('no runnerResult generated by Lighthouse');
}
// Report is always a singular string since {output: 'html'}, above.
const reportHtml = /** @type {string} */ (runnerResult.report);
const blobURL = createReportPageAsBlob(reportHtml);
await new Promise(resolve => chrome.windows.create({url: blobURL}, resolve));
}
/**
* @param {string} reportHtml
* @return {string} Blob URL of the report (or error page) HTML
*/
function createReportPageAsBlob(reportHtml) {
performance.mark('report-start');
const blob = new Blob([reportHtml], {type: 'text/html'});
const blobURL = URL.createObjectURL(blob);
performance.mark('report-end');
performance.measure('generate report', 'report-start', 'report-end');
return blobURL;
}
/**
* Save currently selected set of category categories to local storage.
* @param {{selectedCategories: Array<string>, useDevTools: boolean}} settings
*/
function saveSettings(settings) {
const storage = {
/** @type {Record<string, boolean>} */
[STORAGE_KEY]: {},
/** @type {Record<string, boolean>} */
[SETTINGS_KEY]: {},
};
// Stash selected categories.
getDefaultCategories().forEach(category => {
storage[STORAGE_KEY][category.id] = settings.selectedCategories.includes(category.id);
});
// Stash throttling setting.
storage[SETTINGS_KEY].useDevTools = settings.useDevTools;
// Save object to chrome local storage.
chrome.storage.local.set(storage);
}
/**
* Load selected category categories from local storage.
* @return {Promise<{selectedCategories: Array<string>, useDevTools: boolean}>}
*/
function loadSettings() {
return new Promise(resolve => {
// Protip: debug what's in storage with:
// chrome.storage.local.get(['lighthouse_audits'], console.log)
chrome.storage.local.get([STORAGE_KEY, SETTINGS_KEY], result => {
// Start with list of all default categories set to true so list is
// always up to date.
/** @type {Record<string, boolean>} */
const defaultCategories = {};
getDefaultCategories().forEach(category => {
defaultCategories[category.id] = true;
});
// Load saved categories and settings, overwriting defaults with any
// saved selections.
const savedCategories = Object.assign(defaultCategories, result[STORAGE_KEY]);
const defaultSettings = {
useDevTools: false,
};
const savedSettings = Object.assign(defaultSettings, result[SETTINGS_KEY]);
resolve({
useDevTools: !!savedSettings.useDevTools,
selectedCategories: Object.keys(savedCategories).filter(cat => savedCategories[cat]),
});
});
});
}
/** @param {(status: [string, string, string]) => void} listenCallback */
function listenForStatus(listenCallback) {
log.events.addListener('status', function(log) {
latestStatusLog = log;
listenCallback(log);
});
// Show latest saved status log to give immediate feedback
// when reopening the popup message when lighthouse is running
if (lighthouseIsRunning && latestStatusLog) {
listenCallback(latestStatusLog);
}
}
function isRunning() {
return lighthouseIsRunning;
}
// Run when in extension context, but not in unit tests.
if (typeof window !== 'undefined' && 'chrome' in window && chrome.runtime) {
chrome.runtime.onInstalled.addListener(details => {
if (details.previousVersion) {
// eslint-disable-next-line no-console
console.log('previousVersion', details.previousVersion);
}
});
}
if (typeof module !== 'undefined' && module.exports) {
// Export for importing types into popup.js and require()ing into unit tests.
module.exports = {
runLighthouseInExtension,
getDefaultCategories,
isRunning,
listenForStatus,
saveSettings,
loadSettings,
};
}
// Expose on window for extension (popup.js), other browser-residing consumers of file.
if (typeof window !== 'undefined') {
// @ts-ignore
window.runLighthouseInExtension = runLighthouseInExtension;
// @ts-ignore
window.getDefaultCategories = getDefaultCategories;
// @ts-ignore
window.isRunning = isRunning;
// @ts-ignore
window.listenForStatus = listenForStatus;
// @ts-ignore
window.loadSettings = loadSettings;
// @ts-ignore
window.saveSettings = saveSettings;
}