user1862965
user1862965

Reputation: 386

module.exports for functions with multiple puppeteer actions does not work

I have code in file login.js

   const puppeteer = require('puppeteer');
const configpass = require("./config.json");
const login_helper = require("./login_helper");

(async () => {
  const browser = await puppeteer.launch({
    args: ["--no-sandbox"],
    headless: false,
    slowMo: 30
  })
  const page = await browser.newPage()
  await page.setViewport({ width: 1920, height: 1080 })

  const navigationPromise = page.waitForNavigation({
    waitUntil: "networkidle0"
  });


  await login_helper.login_function(page, configpass.username, configpass.password);

  await navigationPromise


  await page.waitForSelector('.container > .row > .col-md-4 > p > a')
  await page.click('.container > .row > .col-md-4 > p > a')

  await navigationPromise

  //await browser.close()
})()

and i want to create one function in external file with many action just like in file login_helper.js

    module.exports = {

    login_function: async (page, username, password) => {
        page.goto('http://quotes.toscrape.com/');

        page.waitForSelector('.container > .row > .col-md-4 > p > a');
        page.click('.container > .row > .col-md-4 > p > a');
        page.waitForSelector('.container #username');
        page.click('.container #username');
        page.type(
            ".container #username", username
        );

        page.waitForSelector('.container #password');
        page.click('.container #password');
        page.type(".container #password", password
        );
        page.waitForSelector('body > .container > form > .btn')
        page.click('body > .container > form > .btn')
        return page;
    }
};

I am getting error, why?

UnhandledPromiseRejectionWarning: Error: Execution context was destroyed, most likely because of a navigation.

tnx a lot

Upvotes: 0

Views: 1703

Answers (1)

Philipp Claßen
Philipp Claßen

Reputation: 43950

Puppeteer returns promises. You should call await, otherwise, the control flow will not be as you expected. You expect the code to finish each statement, before continuing with the next, but without await, it will immediately start the next one while the first one has not finished yet.

For example, instead of

page.goto('http://quotes.toscrape.com/');

try

await page.goto('http://quotes.toscrape.com/');

In addition, errors will not be handled. That is why you get the UnhandledPromiseRejectionWarning exception. Try to add await before all interactions with page (for details, check the API, but I think, in your case, every call returns a promise).

Upvotes: 1

Related Questions