Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Puppeteer invoking onChange event handler not working

Banging my head against this wall for a bit, hoping someone may have some advice.

I am trying to invoke the onChange handler in a page loaded into Puppeteer. While I am able to select the appropriate option within the select (verified by turning off headless) I am unable to get the event handler to run.

1) Puppeteer provides the page.select() method, which explicitly states

"Triggers a change and input event once all the provided options have been selected"

I am able to select the expected option, but the event handler does not fire

await page.select('select#venue', '40');

2) Using native javascript inside a page.evaluate() call to manually select the required option, then generate a new Event and manually using element.dispatchEvent(event) e.g.

document.querySelector('select#venue > option:nth-child(4)').selected = "selected";

const event = new Event('change', {bubbles: true});
event.simulated = true;

document.querySelector('select#venue').dispatchEvent(event));

3) Using jQuery inside a page.evaluate() call to manually select the required otpion, then trigger the event e.g.

$("select#venue").val(17).change();

Completely out of ideas folks, and thoughts appreciated!

like image 552
Shaun Hurley Avatar asked Jul 02 '18 21:07

Shaun Hurley


1 Answers

I was searching for same thing, to trigger an "onchange" event on a text field. I modified your code a little and it worked:

const myValue = 17;
await page.$eval('#selector', (element, myValue) => {
    element.value = myValue;
    const event = new Event('change');
    element.dispatchEvent(event);
}, myValue);
like image 103
Ilya Shevyryaev Avatar answered Nov 08 '22 00:11

Ilya Shevyryaev