Generate Click Events
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
We can do exactly the same thing with the location hack, like so:
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.
The same thing applies to
If a page has an element like:
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
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);