Generate Click Events: Difference between revisions

From GreaseSpot Wiki
Jump to navigationJump to search
Blanked the page
Line 1: Line 1:
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 <code>onclick</code> 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 <code>onclick</code> attribute.
We can do exactly the same thing with the [[location hack]], like so:
<pre class='sample'>
// Assume "a" contains a reference to the <a> tag shown above.
location.assign( "javascript:" + a.getAttribute("onclick") + ";void(0)" );
</pre>
Even if the site changes the scripts on the page, as long as your user script can still find the <code><a></code> element, it can run the <code>onclick</code> code defined there.
== Following javascript: Links ==
The same thing applies to <code>javascript:</code> links.
If a page has an element like:
<pre>
<a href="javascript:window.open('http://www.example.com/');void(0)">Click Here</a>
</pre>
You can do the same thing, based on the href attribute (which is already formatted properly for you):
<pre class='sample'>
location.assign( a.getAttribute('href') );
</pre>
== 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 <code>addEventListener()</code> 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 <code>el</code> variable points to some element which we want to "click on":
<pre class='sample'>
var evt = document.createEvent("MouseEvents");
evt.initEvent("click", true, true);
el.dispatchEvent(evt);
</pre>
See also:
* https://developer.mozilla.org/en/DOM/document.createEvent
* https://developer.mozilla.org/En/DOM/Element.dispatchEvent
[[Category:Coding Tips:Interacting With The Page]]

Revision as of 07:33, 1 August 2011