How to simulate a click by using x,y coordinates in JavaScript?

前端 未结 5 1443
闹比i
闹比i 2020-11-22 15:29

Is it possible to use given coordinates in order to simulate a click in JavaScript within a webpage?

相关标签:
5条回答
  • 2020-11-22 15:31

    You can dispatch a click event, though this is not the same as a real click. For instance, it can't be used to trick a cross-domain iframe document into thinking it was clicked.

    All modern browsers support document.elementFromPoint and HTMLElement.prototype.click(), since at least IE 6, Firefox 5, any version of Chrome and probably any version of Safari you're likely to care about. It will even follow links and submit forms:

    document.elementFromPoint(x, y).click();
    

    https://developer.mozilla.org/En/DOM:document.elementFromPoint https://developer.mozilla.org/en-US/docs/Web/API/HTMLElement/click

    0 讨论(0)
  • 2020-11-22 15:32

    This is just torazaburo's answer, updated to use a MouseEvent object.

    function click(x, y)
    {
        var ev = new MouseEvent('click', {
            'view': window,
            'bubbles': true,
            'cancelable': true,
            'screenX': x,
            'screenY': y
        });
    
        var el = document.elementFromPoint(x, y);
    
        el.dispatchEvent(ev);
    }
    
    0 讨论(0)
  • 2020-11-22 15:38

    it doenst work for me but it prints the correct element to the console

    this is the code:

    function click(x, y)
    {
        var ev = new MouseEvent('click', {
            'view': window,
            'bubbles': true,
            'cancelable': true,
            'screenX': x,
            'screenY': y
        });
    
        var el = document.elementFromPoint(x, y);
        console.log(el); //print element to console
        el.dispatchEvent(ev);
    }
    click(400, 400);
    
    0 讨论(0)
  • 2020-11-22 15:40

    For security reasons, you can't move the mouse pointer with javascript, nor simulate a click with it.

    What is it that you are trying to accomplish?

    0 讨论(0)
  • 2020-11-22 15:58

    Yes, you can simulate a mouse click by creating an event and dispatching it:

    function click(x,y){
        var ev = document.createEvent("MouseEvent");
        var el = document.elementFromPoint(x,y);
        ev.initMouseEvent(
            "click",
            true /* bubble */, true /* cancelable */,
            window, null,
            x, y, 0, 0, /* coordinates */
            false, false, false, false, /* modifier keys */
            0 /*left*/, null
        );
        el.dispatchEvent(ev);
    }
    

    Beware of using the click method on an element -- it is widely implemented but not standard and will fail in e.g. PhantomJS. I assume jQuery's implemention of .click() does the right thing but have not confirmed.

    0 讨论(0)
提交回复
热议问题