Puppeteer's `page.evaluate` result differs from devTools console

I need to check for a certain service worker being registered. Unfortunately, page.evaluate returns undefined no matter what I do.

let page = await chrome.newPage();
await page.goto('http://127.0.0.1:8089/');
await page.waitFor(10000);

const isCorrectSW = await page.evaluate(async () => {
    await navigator
        .serviceWorker
        .getRegistrations()
        .then(registrations =>
            registrations[0].active.scriptURL.endsWith('/target.js')
        );
});
console.log(isCorrectSW);

isCorrectSW ends up being undefined, but if I enable devtools and run the same statement in the Chromium instance’s devtools, I get the correct result. I can also observe the service worker attached in the browser’s dev tools.

Is this a Puppeteer bug, or am I doing something incorrectly?

>Solution :

According to the documentation, page.evaluate returns undefined when the function passed returns a non-serializable value.

In your scenario, the function you are passing into page.evaulate does not return anything.

You are already using async, you can switch the function you are passing to be:

async () => {
    const registrations = await navigator.serviceWorker.getRegistrations()
    return registrations[0].active.scriptURL.endsWith('/target.js')
}

Leave a Reply