Capture events by reference

I am trying to track clicks on an external link (without using the redirect page).

How can I capture an event when a user clicks on a link, regardless of whether the user is:

  1. Left click on the link
  2. Right-click the link and open it in a new window.
  3. Use the keyboard to activate the link.
  4. Are there other ways to activate the link?

The onClick event applies only to the first.

When setting href="javascript:fireEventAndFollowLink()" user will not be able to open the link in a new window (2), so this is not a solution.

+9
source share
1 answer

A link can be launched in several ways (if using modern browsers, see note):

  1. Left click
    • For <a target="_blank"> or <a target="_new"> page will be loaded into a new tab .
    • When the user presses CTRL , the page will be loaded into 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 into the current screen or another frame .
  2. Midde click
    • The page will be loaded into a new tab, regardless of the modifier keys.
  3. Right click
    This method is incredibly complicated, if not impossible, to fully implement .
    JavaScript cannot be used to directly determine which option is selected in the context menu.
    • If you select "Open link in new (tab, window)", the page will load into a new tab, window.
    • If you don’t select any of them, nothing loads
  4. Keyboard:
    • Context menu (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 button used can be tracked using the event.button (or event.which ) event.which . 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 properties event.altKey and event.shiftKey .
  • oncontextmenu event can be used to capture 3
  • The onkeydown event can be used to capture 4.

The behavior of modifier keys is not formalized in any specification and, therefore, depends on the browser. At least Firefox (at least 3+) and Chrome (all?) Implement this key behavior.

Related question - How to intercept the action on the link ( <a> )?

+14
source

Source: https://habr.com/ru/post/925103/


All Articles