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

How to Simulate a Click in PhantomJS?

Susan Sarandon
Susan SarandonOriginal
2024-12-05 09:52:091012browse

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();  
});

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);
}

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

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

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!

Statement:
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