admin 管理员组

文章数量: 1087675

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.

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.

Share Improve this question edited Jun 3, 2014 at 23:28 Brock Adams 93.4k23 gold badges240 silver badges303 bronze badges asked Jun 3, 2014 at 21:24 user3699068user3699068 7552 gold badges7 silver badges7 bronze badges 6
  • you can use document.createEvent("MouseEvents") to simulate a click. – dandavis Commented Jun 3, 2014 at 22:07
  • I thought this was only for things such as scroll wheel – user3699068 Commented Jun 3, 2014 at 22:13
  • 4 developer.mozilla.org/en-US/docs/Web/API/… – dandavis Commented Jun 3, 2014 at 22:14
  • I dont understand how its simulating a whole mouse click without mousedown or mouseup =/ I dont know if what im trying to do is pointless or im just going about it the wrong way, basically I have a button that only works on mouseup. – user3699068 Commented Jun 3, 2014 at 22:24
  • 3 Woo!!! The mozilla dev site did it for me. The key for me was: var simMousedownEvent = new MouseEvent('mousedown', { 'view': window, 'bubbles': true, 'cancelable': true }); $(“input.myelement”)[0].dispatchEvent(simMousedownEvent) The [0] is needed to convert from jQuery object to native JS DOM object. – redfox05 Commented Jul 2, 2015 at 15:36
 |  Show 1 more comment

3 Answers 3

Reset to default 141

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 = new Event(eventType, { bubbles: true, cancelable: 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:

  • "Normal" button-clicking approaches are not working in Greasemonkey script?
  • Choosing and activating the right controls on an AJAX-driven site

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

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

I improved Brock's code a little after it worked as expected for me.

Definition:

function simulateMouseClick(targetNode) {
    function triggerMouseEvent(targetNode, eventType) {
        var clickEvent = document.createEvent('MouseEvents');
        clickEvent.initEvent(eventType, true, true);
        targetNode.dispatchEvent(clickEvent);
    }
    ["mouseover", "mousedown", "mouseup", "click"].forEach(function(eventType) { 
        triggerMouseEvent(targetNode, eventType);
    });
}

Calling examples:

simulateMouseClick(document);

simulateMouseClick(document.querySelector("a[href*='stackoverflow']"));

Bit Optimized

function fireMouseEvents( query, eventNames ){
    var element = document.querySelector(query);
    if(element && eventNames && eventNames.length){
        for(var index in eventNames){
            var eventName = eventNames[index];
            if(element.fireEvent ){
                element.fireEvent( 'on' + eventName );     
            } else {   
                var eventObject = document.createEvent( 'MouseEvents' );
                eventObject.initEvent( eventName, true, false );
                element.dispatchEvent(eventObject);
            }
        }
    }
}

You would fire like this

fireMouseEvents("a[href*='stackoverflow']",['mouseover','mousedown','mouseup','click']);

本文标签: javascriptSimulating a mousedown click mouseup sequence in TampermonkeyStack Overflow