Home >Web Front-end >JS Tutorial >How to Simulate Clicks on Elements (e.g., Spans) Using PhantomJS?
PhantomJS: Simulating Element Clicks
Context:
When attempting to click an element using PhantomJS's page.evaluate function, you may encounter an error related to undefined being invoked as a function. This occurs when the target element is a span rather than a native input button.
Solution:
To resolve this issue and simulate a click on an arbitrary element, utilize the following custom function:
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); }
This function creates a synthetic mouse click event and dispatches it to the specified element. By using it in conjunction with page.evaluate, you can effectively simulate the click action:
page.evaluate(function() { click(document.getElementById('idButtonSpan')); });
Additional Notes:
The above is the detailed content of How to Simulate Clicks on Elements (e.g., Spans) Using PhantomJS?. For more information, please follow other related articles on the PHP Chinese website!