I am trying to track clicks on an external link (without using a "redirect page").
How can I capture an event when a user follows a link, regardless of whether the user:
- Left clicks on the link
- Right clicks on the link and open it in a new window
- Use the keyboard to activate the link
- Is there other ways to activate a link?
The onClick event only applies to the first.
If setting href="javascript:fireEventAndFollowLink()"
the user will not be able to open the link in a new window (2), so this is not a solution.
A link can be triggered in some ways (assuming modern browsers, see foot note):
<a target="_blank">
or<a target="_new">
, the page will be loaded in a new tab.target
values, the link can be loaded in the current screen or another frame.This method is incredibly hard, if not impossible to fully implement.
JavaScript cannot be used to directly detect which option in the contextmenu has selected.
How to capture these links
There is no reliable way to capture all link events.
onmouseup
event can be used to detect 1, 2, and 3.The used button can be tracked through the
event.button
(orevent.which
) property. In all non-IE browsers, 0=Left, 1=Middle, 2=Right. In IE, 1=Left, 2=Middle, 4=Right.onclick
event can be used to capture 1 and 2.The modifier key can be detected through the
event.altKey
andevent.shiftKey
properties.oncontextmenu
event can be used to capture 3onkeydown
event can be used to capture 4.The behaviour of the modifier keys is not formalized in any specification, and is thus browser-specific. At least Firefox (at least 3+) and Chrome (all?) implement this key behaviour.
Related question - How to intercept an action on a link (
<a>
)?