0
# Core Auditing
1
2
Core auditing functions provide the primary interface for running Lighthouse audits in different measurement modes. These functions form the foundation of Lighthouse's auditing capabilities.
3
4
## Capabilities
5
6
### Main Lighthouse Function
7
8
The primary entry point for running Lighthouse audits on web pages.
9
10
```javascript { .api }
11
/**
12
* Run Lighthouse audit on a URL
13
* @param url - URL to test (optional if running in audit mode)
14
* @param flags - Optional runtime settings and configuration flags
15
* @param config - Configuration for the Lighthouse run
16
* @param page - Puppeteer page instance for testing
17
* @returns Promise resolving to RunnerResult with audit results
18
*/
19
function lighthouse(
20
url?: string,
21
flags?: LH.Flags,
22
config?: LH.Config,
23
page?: LH.Puppeteer.Page
24
): Promise<LH.RunnerResult | undefined>;
25
```
26
27
**Usage Examples:**
28
29
```javascript
30
import lighthouse from 'lighthouse';
31
import * as chromeLauncher from 'chrome-launcher';
32
33
// Basic audit
34
const chrome = await chromeLauncher.launch({chromeFlags: ['--headless']});
35
const result = await lighthouse('https://example.com', {
36
logLevel: 'info',
37
output: 'json',
38
port: chrome.port,
39
});
40
console.log('Performance score:', result.lhr.categories.performance.score);
41
await chrome.kill();
42
43
// With custom configuration
44
const customConfig = {
45
extends: 'lighthouse:default',
46
settings: {onlyCategories: ['performance', 'accessibility']},
47
};
48
49
const result = await lighthouse('https://example.com', {
50
port: chrome.port,
51
}, customConfig);
52
```
53
54
### Navigation Auditing
55
56
Runs navigation-based audit, measuring page load performance and gathering artifacts during page navigation.
57
58
```javascript { .api }
59
/**
60
* Run navigation-based audit on a page
61
* @param page - Puppeteer page instance (optional)
62
* @param requestor - Navigation target (URL string or navigation function)
63
* @param options - Configuration and flags for the audit
64
* @returns Promise resolving to RunnerResult with navigation audit results
65
*/
66
function navigation(
67
page?: LH.Puppeteer.Page,
68
requestor?: LH.NavigationRequestor,
69
options?: { config?: LH.Config; flags?: LH.Flags }
70
): Promise<LH.RunnerResult | undefined>;
71
```
72
73
**Usage Examples:**
74
75
```javascript
76
import { navigation } from 'lighthouse';
77
import puppeteer from 'puppeteer';
78
79
const browser = await puppeteer.launch();
80
const page = await browser.newPage();
81
82
// Navigation audit with URL
83
const result = await navigation(page, 'https://example.com', {
84
flags: {logLevel: 'info'},
85
config: {settings: {onlyCategories: ['performance']}},
86
});
87
88
// Navigation audit with custom navigation function
89
const result = await navigation(page, async () => {
90
await page.goto('https://example.com');
91
await page.waitForSelector('.main-content');
92
}, {
93
flags: {throttlingMethod: 'simulate'},
94
});
95
96
await browser.close();
97
```
98
99
### Timespan Auditing
100
101
Starts a timespan measurement session for analyzing user interactions and dynamic content changes.
102
103
```javascript { .api }
104
/**
105
* Start timespan measurement session
106
* @param page - Puppeteer page instance where measurements will occur
107
* @param options - Configuration and flags for the timespan measurement
108
* @returns Promise resolving to object with endTimespan function
109
*/
110
function startTimespan(
111
page: LH.Puppeteer.Page,
112
options?: { config?: LH.Config; flags?: LH.Flags }
113
): Promise<{ endTimespan: () => Promise<LH.RunnerResult | undefined> }>;
114
```
115
116
**Usage Examples:**
117
118
```javascript
119
import { startTimespan } from 'lighthouse';
120
import puppeteer from 'puppeteer';
121
122
const browser = await puppeteer.launch();
123
const page = await browser.newPage();
124
await page.goto('https://example.com');
125
126
// Measure user interaction
127
const session = await startTimespan(page, {
128
flags: {logLevel: 'info'},
129
});
130
131
// Perform user interactions
132
await page.click('.search-button');
133
await page.type('input[type="search"]', 'lighthouse');
134
await page.keyboard.press('Enter');
135
await page.waitForSelector('.search-results');
136
137
// End measurement and get results
138
const result = await session.endTimespan();
139
console.log('CLS during interaction:', result.lhr.audits['cumulative-layout-shift'].score);
140
141
await browser.close();
142
```
143
144
### Snapshot Auditing
145
146
Takes a snapshot audit of the current page state without navigation or user interaction.
147
148
```javascript { .api }
149
/**
150
* Take snapshot audit of current page state
151
* @param page - Puppeteer page instance to audit
152
* @param options - Configuration and flags for the snapshot audit
153
* @returns Promise resolving to RunnerResult with snapshot audit results
154
*/
155
function snapshot(
156
page: LH.Puppeteer.Page,
157
options?: { config?: LH.Config; flags?: LH.Flags }
158
): Promise<LH.RunnerResult | undefined>;
159
```
160
161
**Usage Examples:**
162
163
```javascript
164
import { snapshot } from 'lighthouse';
165
import puppeteer from 'puppeteer';
166
167
const browser = await puppeteer.launch();
168
const page = await browser.newPage();
169
await page.goto('https://example.com');
170
171
// Take snapshot after page interactions
172
await page.evaluate(() => {
173
// Modify page state
174
document.body.classList.add('dark-theme');
175
});
176
177
const result = await snapshot(page, {
178
flags: {logLevel: 'info'},
179
config: {settings: {onlyCategories: ['accessibility', 'best-practices']}},
180
});
181
182
console.log('Accessibility score:', result.lhr.categories.accessibility.score);
183
await browser.close();
184
```
185
186
### Utility Functions
187
188
Additional utility functions for working with audit results and configurations.
189
190
```javascript { .api }
191
/**
192
* Get list of available audits
193
* @returns Array of audit definitions with metadata
194
*/
195
function getAuditList(): LH.Config.AuditDefn[];
196
```
197
198
**Usage Examples:**
199
200
```javascript
201
import { getAuditList } from 'lighthouse';
202
203
// Get all available audits
204
const audits = getAuditList();
205
console.log('Available audits:', audits.map(audit => audit.path));
206
207
// Filter audits by category
208
const performanceAudits = audits.filter(audit =>
209
audit.options && audit.options.category === 'performance'
210
);
211
```
212
213
## Configuration Options
214
215
### Flags Interface
216
217
Runtime configuration flags that control Lighthouse behavior:
218
219
```javascript { .api }
220
interface LH.Flags {
221
// Core options
222
port?: number; // Chrome debugging port
223
hostname?: string; // Chrome debugging hostname
224
output?: LH.OutputMode | LH.OutputMode[]; // Output format(s)
225
outputPath?: string; // Output file path
226
view?: boolean; // Open report in browser
227
configPath?: string; // Path to config file
228
preset?: 'perf' | 'desktop'; // Quick preset configs
229
230
// Chrome options
231
chromeFlags?: string | string[]; // Chrome browser flags
232
maxWaitForLoad?: number; // Navigation timeout (ms)
233
234
// Throttling options
235
throttlingMethod?: 'provided' | 'devtools' | 'simulate';
236
throttling?: LH.ThrottlingSettings;
237
238
// Audit filtering
239
onlyAudits?: string[]; // Run only specified audits
240
skipAudits?: string[]; // Skip specified audits
241
onlyCategories?: string[]; // Run only specified categories
242
243
// Other options
244
logLevel?: 'silent' | 'error' | 'info' | 'verbose';
245
enableErrorReporting?: boolean; // Enable error reporting to Google
246
}
247
```
248
249
### Navigation Requestor Types
250
251
Navigation requestor can be a URL string or a navigation function:
252
253
```javascript { .api }
254
type LH.NavigationRequestor = string | (() => Promise<void>);
255
```
256
257
**Examples:**
258
259
```javascript
260
// URL string requestor
261
const urlRequestor = 'https://example.com';
262
263
// Function requestor for complex navigation
264
const functionRequestor = async () => {
265
await page.goto('https://example.com/login');
266
await page.type('#username', 'testuser');
267
await page.type('#password', 'password');
268
await page.click('#login-button');
269
await page.waitForNavigation();
270
};
271
```
272
273
## Error Handling
274
275
Core auditing functions may throw or return results with errors:
276
277
```javascript
278
try {
279
const result = await lighthouse('https://example.com', flags);
280
281
// Check for runtime errors
282
if (result.lhr.runtimeError) {
283
console.error('Runtime error:', result.lhr.runtimeError);
284
}
285
286
// Check for run warnings
287
if (result.lhr.runWarnings.length > 0) {
288
console.warn('Run warnings:', result.lhr.runWarnings);
289
}
290
291
} catch (error) {
292
console.error('Lighthouse error:', error.message);
293
}
294
```