Attempts to click an element using .click() often fail in PhantomJS, resulting in errors like "undefined is not a function...". This issue arises because .click() is not part of the standard DOM specification.
To successfully click an element, it is necessary to create and dispatch an event as follows:
function click(el) { var ev = document.createEvent("MouseEvent"); ev.initMouseEvent( "click", true /* bubble */, true /* cancelable */, window, null, 0, 0, 0, 0, /* coordinates */ false, false, false, false, /* modifier keys */ 0 /*left*/, null ); el.dispatchEvent(ev); }
Then, you can use this function to click the desired span element by passing it as an argument:
click(document.getElementById('idButtonSpan'));
This approach simulates a mouse click event, allowing you to successfully click elements even if they do not have built-in click functionality, addressing the limitations faced with Casper in this specific scenario.
The above is the detailed content of Why Does `.click()` Fail in PhantomJS and How Can I Properly Click Elements?. For more information, please follow other related articles on the PHP Chinese website!