Generate Click Events: Difference between revisions
m Reverted edits by 68.118.179.93 (talk) to last revision by 195.188.8.1 |
|||
(3 intermediate revisions by 3 users not shown) | |||
Line 24: | Line 24: | ||
If a page has an element like: | If a page has an element like: | ||
<pre | <pre> | ||
<a href="javascript:window.open('http://www.example.com/');void(0)">Click Here</a> | <a href="javascript:window.open('http://www.example.com/');void(0)">Click Here</a> | ||
</pre> | </pre> | ||
Line 41: | Line 41: | ||
<pre class='sample'> | <pre class='sample'> | ||
var evt = document.createEvent(" | var evt = document.createEvent("MouseEvents"); | ||
evt.initEvent("click", true, true); | evt.initEvent("click", true, true); | ||
el.dispatchEvent(evt); | el.dispatchEvent(evt); |
Latest revision as of 13:16, 1 August 2011
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: