imlearningcode
imlearningcode

Reputation: 411

nodejs How to fix `browser.newPage is not a function` using puppeteer-core?

I am trying to use pupetteer-core but when I run my code.

const puppeteer = require('puppeteer-core');
module.exports= run = () => {
    const url = 'https://example.com'
    const browser = puppeteer.launch();
    const page = browser.newPage().then(function(page){
    page.goto(url)
    return browser
};

run().catch(console.error.bind(console))

I get this error TypeError: browser.newPage is not a function

Upvotes: 1

Views: 9000

Answers (1)

Thomas Dondorf
Thomas Dondorf

Reputation: 25270

The problem in your code is that puppeteer works with Promises, meaning that most functions will return a Promise instead of the value directly. This means that you ether have to use then function or await statements to get the value.

Code sample

module.exports = run = async () => {
    const url = 'https://example.com';
    const browser = await puppeteer.launch();
    const page = await browser.newPage();
    await page.goto(url);
    return browser;
};

Note that the function is marked as async now, making it implicitly returning a Promise. That means to wait for the run() function to finish, you would have to call it from within another async function like this:

(async () => {
    const browser = await run();
})();

Upvotes: 5

Related Questions