Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
180 views
Welcome To Ask or Share your Answers For Others

1 Answer

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>)?


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...