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?