Simulating click with javascript on document

后端 未结 2 1918
无人及你
无人及你 2020-12-30 12:17

Is it possible to simulate a click on a webpage using javascript but without defining a specific element, but rather just specifying the document?

I would have liked

相关标签:
2条回答
  • 2020-12-30 12:56

    window.dispatchEvent should do the trick.

    <script>
    function simulateClick() {
      var evt = document.createEvent("Events");
      evt.initEvent("click", true, true);
      window.dispatchEvent(evt);
    }
    addEventListener('click',function(){alert('test');},false);
    </script>
    <button onclick="simulateClick();">Go</button>
    

    Or... with extra MouseEvents information:

    <script>
    function simulateClick() {
      var evt = document.createEvent("MouseEvents");
      evt.initMouseEvent("click", true, true, window, 1, 12, 345, 7, 220, false, false, true, false, 0, null);
      window.dispatchEvent(evt);
    }
    addEventListener('click',function(){alert('test');},false);
    </script>
    <button onclick="simulateClick();">Go</button>
    

    The above examples will cause a click to be simulated on window when the button is clicked. An event listener is added to window to alert when clicked, so therefore clicking the button will indirectly trigger an alert.

    More info: http://www.howtocreate.co.uk/tutorials/javascript/domevents

    0 讨论(0)
  • 2020-12-30 13:00

    In case anyone bumps into this looking for a framework agnostic way to fire any HTML and Mouse event (and set some options, if needed), have a look here: How to simulate a mouse click using JavaScript?

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