Simulating a mousedown, click, mouseup sequence in Tampermonkey?

user3699068 picture user3699068 · Jun 3, 2014 · Viewed 54.2k times · Source

I would like to simulate a whole click not just

document.getElementsByClassName()[0].click();

How do I do that? Search results all seem to be about handling such events, not triggering them.

Answer

Brock Adams picture Brock Adams · Jun 4, 2014

Send mouse events. Like so:

//--- Get the first link that has "stackoverflow" in its URL.
var targetNode = document.querySelector ("a[href*='stackoverflow']");
if (targetNode) {
    //--- Simulate a natural mouse-click sequence.
    triggerMouseEvent (targetNode, "mouseover");
    triggerMouseEvent (targetNode, "mousedown");
    triggerMouseEvent (targetNode, "mouseup");
    triggerMouseEvent (targetNode, "click");
}
else
    console.log ("*** Target node not found!");

function triggerMouseEvent (node, eventType) {
    var clickEvent = document.createEvent ('MouseEvents');
    clickEvent.initEvent (eventType, true, true);
    node.dispatchEvent (clickEvent);
}

That works if the web page is statically loaded. If the web page is AJAX-driven, use a technique as in:


Beware:
The question code has an error. You need to pass a class name to that function. Like so:

document.getElementsByClassName ("SomeClassName")[0].click();