Home > Web Front-end > JS Tutorial > How to Simulate a Click in PhantomJS?

How to Simulate a Click in PhantomJS?

Susan Sarandon
Release: 2024-12-05 09:52:09
Original
1027 people have browsed it

How to Simulate a Click in PhantomJS?

Clicking an Element in PhantomJS

To click an element in PhantomJS, the standard .click() method is not supported. Instead, an event must be created and dispatched.

Consider the following code:

page.evaluate(function() {
    document.getElementById('idButtonSpan').click();  
});
Copy after login

This code will result in an error because .click() is not a function. To resolve this, create an event and dispatch it:

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);
}
Copy after login

Then, you can use this function to click an element:

page.evaluate(function() {
    click(document.getElementById('idButtonSpan'));  
});
Copy after login

The above is the detailed content of How to Simulate a Click in PhantomJS?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template