You can hook into Puppeteer's page navigation using the hooks configuration. The puppeteer:before-goto hook allows you to execute logic before the browser navigates to a URL.
Set localStorage before navigation
Use page.evaluateOnNewDocument within the hook to inject data like authentication tokens into the browser context before the page loads.
Modify Page Content
You can use the hook to wait for navigation and then use page.evaluate to manipulate the DOM, such as removing elements (e.g., cookie banners) that might interfere with Lighthouse metrics like CLS.
// Set localStorage before navigation
export default defineUnlighthouseConfig({
hooks: {
'puppeteer:before-goto': async (page) => {
await page.evaluateOnNewDocument((token) => {
localStorage.setItem('auth', token)
}, process.env.AUTH_TOKEN)
},
},
})
// Remove elements that cause CLS
export default defineUnlighthouseConfig({
hooks: {
'puppeteer:before-goto': async (page) => {
page.waitForNavigation().then(async () => {
await page.evaluate(() => {
document.querySelector('.cookie-banner')?.remove()
})
})
},
},
})