Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Use Puppeteer in class methods

i am asking if it is possible i could use Puppeteer in class methods. I read a lot about async/await functions but i could not find anything regarding classes. I currently have this:

class Tools{
  async login() {
    this.browser = ppt.launch({
      headless: true,
    });
    this.page = this.browser.newPage();
    this.page.type('#email','test');
   ...
  }

Main method:

(async function main() {
  try {

    const tools = await new Tools();
  } catch(e) {
    console.log('Error: ' + e);
  }
})();

Any advice on this?


2 Answers

You are just calling the constructor in your code. You also need to call the login function. Also you don't want to put the await in front of your constructor but in front of login.

Code

const tools = new Tools();
await tools.login();

About async constructor functions

Be aware that you cannot use constructor calls (new Tools) with await. The reason is, that await waits for the returned Promise to be resolved. But constructor functions cannot return a Promise as they need to return the newly created object.

That's why libraries like puppeteer use factory functions like puppeteer.launch. These functions will create an object in addition to calling asynchronous functions afterwards. If you want to do something similar in your code, you can do it like this:

class Tools {
  async initialize() {
    // ...
  }
  static async create() {
    const newObject = new Tools();
    await newObject.initialize();
  }
}


const tools = await Tools.create();
like image 56
Thomas Dondorf Avatar answered Sep 17 '25 23:09

Thomas Dondorf


headless: true

Make puppeteer to run in Headless mode, meaning it will execute your code, but you'll not have any chrome openning

if you want to see what's hapenning in real time for debugging purposes, initialize puppeteer without the headleass mode

this.browser = ppt.launch({
  headless: false,
});
like image 20
Jeremie Olivier Avatar answered Sep 17 '25 23:09

Jeremie Olivier