When attempting to click an element in PhantomJS using the page.evaluate function and document.getElementById('idButtonSpan').click();, you may encounter an error stating "undefined is not a function...", even though the element exists. This is because .click() is not a standard function for clicking elements in PhantomJS.
To simulate a click event in PhantomJS, you need to create and dispatch a custom event as follows:
function click(el) { var ev = document.createEvent("MouseEvent"); ev.initMouseEvent( "click", true, // bubble true, // cancelable window, null, 0, // screenX 0, // screenY 0, // clientX 0, // clientY false, // ctrlKey false, // altKey false, // shiftKey false, // metaKey 0, // button null // relatedTarget ); el.dispatchEvent(ev); }
You can then use this click function on the desired element to simulate a click event.
The above is the detailed content of How to Properly Simulate Click Events in PhantomJS?. For more information, please follow other related articles on the PHP Chinese website!