0

I'm writing some utility functions for puppeteer to speed up workflow. I want to assign callback functions to dynamically created event listeners. Here's my code so far --

const puppeteer = require('puppeteer');

const listeners = {
  'console': function(consoleObj) {
    console.log(consoleObj.text());
  },
  'dialog': function(dialog) {
    console.log(dialog.message());
  }
};

(async () => {
  const browser = await puppeteer.launch({headless: false});
  const page = await browser.newPage();
  for (var l in listeners) {
    page.on(l, obj => {
      listeners[l](obj)
    });
  }
  var el = await page.evaluate(_ => {
    console.log('page console operational!')
  });
})();

For some reason the page.on() function won't accept dynamically input listener types. Whereas if I input the listener type manually it works (obviously this is not useful because it will just continuously overwrite the 'console' listener) --

for (var l in listeners) {
  page.on('console', obj => {
    listeners[l](obj)
  });
}

How can I go about dynamically creating event listeners with Puppeteer?

BTEVC
  • 151
  • 1
  • 10
  • Your problem is `var`. The `l` in `listeners[l](obj)` is always referring to the last key, `"dialog"`. Use `const` always (`let` for reassignable), never `var`, unless you really know what you're doing. See [What's the difference between using "let" and "var"?](https://stackoverflow.com/questions/762011/whats-the-difference-between-using-let-and-var) – ggorlen Jan 28 '22 at 16:59
  • Does this answer your question? [What's the difference between using "let" and "var"?](https://stackoverflow.com/questions/762011/whats-the-difference-between-using-let-and-var) – ggorlen Jan 28 '22 at 16:59

0 Answers0