Fail to use page instance in a function using puppeteer

167 Views Asked by At

Why does it fail when using using the page instance (not in the same scope as the newPage) in a function ? Appreciate help and explanation.

'use strict'; // see strict mode
var url ='http://example.com';

const puppeteer = require('puppeteer');

(async() => {

const browser = await puppeteer.launch();
const page = await browser.newPage();

    func1(page);        
    browser.close();

 })();

async func1(page) {

     console.log(page);  // output ok
     await page.goto(url, {waitUntil: 'network idle'}); // failed!
}
1

There are 1 best solutions below

0
On

You don't await func1, so browser.close runs before page.goto finishes. 'network idle' should also be 'networkidle' with no space.

'use strict'; // see strict mode
const url = 'http://example.com';

const puppeteer = require('puppeteer');

(async() => {

  const browser = await puppeteer.launch();
  const page = await browser.newPage();

  await func1(page);
  browser.close();

})();

async function func1(page) {

  console.log(page); 
  await page.goto(url, {waitUntil: 'networkidle'});
}