views:

187

answers:

1

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 to do something like this, and if the location happens to have a link, then this will be pressed:

function simulateClick(x, y) 
{
    var evt = window.createEvent("MouseEvents");
    evt.initMouseEvent("click", true, true, window,
        x, y, x, y, 1, false, false, false, false, 0, null);

    window.dispatchEvent(evt);
}
+2  A: 

window.dispatchEvent should do the trick.

<script>
function simulateClick() {
  var evt = window.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 = window.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

Delan Azabani
I want to be able to give the coordinates of the event so that this may be called programmatically form an external framework.
Charlie
Hey there, just added another example with `MouseEvents`-specific data.
Delan Azabani
That's better :-)What is the 'addEventListener' for?
Charlie
It's just part of the example to pop up an alert when the window is clicked (to prove that the event simulation is working)
Delan Azabani