Generate Click Events

From GreaseSpot Wiki
Jump to navigationJump to search

Many web pages execute scripts when the user clicks on elements in the page. Sometimes, you want your user script to trigger this exact same behavior. Here's a few ways to accomplish this.

Invoke onclick Attributes

In the simplest case, the page has an onclick specified on an attribute. For example, YouTube uses a link a bit like this (edited to be shorter, and easier to read):

<a onclick="yt.style.toggle('watch-video-details-toggle-more'); return false;" class="hLink" href="#">more info</a>

When a user clicks this link, the browser executes the script embedded into the onclick attribute. We can do exactly the same thing with the location hack, like so:

// Assume "a" contains a reference to the <a> tag shown above.
location.assign( "javascript:" + a.getAttribute("onclick") + ";void(0)" );

Even if the site changes the scripts on the page, as long as your user script can still find the <a> element, it can run the onclick code defined there.

Following javascript: Links

The same thing applies to javascript: links. If a page has an element like:

<a href="javascript:window.open('http://www.example.com/');void(0)">Click Here</a>

You can do the same thing, based on the href attribute (which is already formatted properly for you):

location.assign( a.getAttribute('href') );

Generating a Click Event

A slightly more complex case involves a page that does not have embedded Javascript code in their page, but rather is using something like addEventListener() to notice and act upon (e.g.) clicks within the document. In this case the above examples will not work, but we can generate a click event, as if the user had clicked their mouse. Assume that the el variable points to some element which we want to "click on":

var evt = document.createEvent("MouseEvents");
evt.initEvent("click", true, true);
el.dispatchEvent(evt);

See also: