Catching event when following a link
Asked Answered
S

1

16

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:

  1. Left clicks on the link
  2. Right clicks on the link and open it in a new window
  3. Use the keyboard to activate the link
  4. 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.

Symons answered 19/1, 2012 at 13:52 Comment(0)
M
18

A link can be triggered in some ways (assuming modern browsers, see foot note):

  1. Left click
    • For <a target="_blank"> or <a target="_new">, the page will be loaded in a new tab.
    • When the user presses CTRL, the page will be loaded in a new tab.
    • When the user presses SHIFT, the page will be loaded in a new window.
    • For other target values, the link can be loaded in the current screen or another frame.
  2. Midde click
    • The page will be loaded in a new tab, regardless of the modifier keys.
  3. Right click
    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.
    • When selecting "Open link in new (tab, window)", the page will load in a new tab, window.
    • When not selecting any of these, nothing loads
  4. Keyboard:
    • Contextmenu (see 3.)
    • Enter - See 1.

How to capture these links
There is no reliable way to capture all link events.

  • The onmouseup event can be used to detect 1, 2, and 3.
    The used button can be tracked through the event.button (or event.which) property. In all non-IE browsers, 0=Left, 1=Middle, 2=Right. In IE, 1=Left, 2=Middle, 4=Right.
  • The onclick event can be used to capture 1 and 2.
    The modifier key can be detected through the event.altKey and event.shiftKey properties.
  • The oncontextmenu event can be used to capture 3
  • The onkeydown 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>)?

Marvismarwin answered 19/1, 2012 at 17:5 Comment(2)
Thank you for the detailed answer. I guess that the only way to be sure to track a click on an external link is to implement some kind of "redirect page" (as Google and Facebook do).Symons
Why do you use onmouseup instead of onmousedown?Doubleganger

© 2022 - 2024 — McMap. All rights reserved.