右键菜单里的链接点击如何跟踪?
|

如何跟踪右键菜单打开链接的行为?

前几天有小伙伴跑来问马老师,客户想跟踪那些右键打开浏览器菜单后去新页面的访客。这虽然这部分占比不多,特别是移动平台上,还是有强迫症的数字营销者想搞明白。

右键菜单里的链接点击如何跟踪?
右键菜单里的链接点击如何跟踪?

因此本篇马老师就提供两种思路来跟踪这些行为。不过我们首先需要搞清楚不管是如何打开的链接,http header的referer字段中的值并不会因此改变。这点我们应该安心。从技术上说直接打开一个链接会触发一个GA4的click事件,而通过右键菜单不会。这也是因为后者没有一个click事件。

第一种思路是通过<a>元素中的链接地址来让目标页面识别这个链接来自右键打开。假设我们的链接HTML代码长这样:

<a href="https://maxket.com/">极诣数字营销</a>

我们可以写一个脚本捕捉右键菜单的事件:

// Get all link elements with a specific href
var links = document.querySelectorAll('a[href="https://maxket.com/"]');

// Add event listener for the contextmenu event to each link
links.forEach(function(link) {
  link.addEventListener('contextmenu', function(e) {
    // Add the parameter to the href when the context menu opens
    if (!link.getAttribute('href').includes('rtclk=true')) {
      var currentHref = link.getAttribute('href');
      var newHref = currentHref + (currentHref.includes('?') ? '&' : '?') + 'rtclk=true';
      link.setAttribute('href', newHref);
    }
  });
  
  // Add event listener for the blur event on each link
  link.addEventListener('blur', function() {
    // Revert the parameter in the href when the context menu closes
    if (link.getAttribute('href').includes('rtclk=true')) {
      var currentHref = link.getAttribute('href');
      var newHref = currentHref.replace('?rtclk=true', '').replace('&rtclk=true', '');
      link.setAttribute('href', newHref);
    }
  });
});

上面代码在右键菜单打开时在目标链接中添加了参数rtclk=true。同时在该菜单消失时去掉了该参数。当用户点击Open link in new tab时,我们就可以让目标页面的GA知道这个访问的来源。

注意上述代码要放到浏览器parse了HTML元素之后才能挂上事件监听器,具体来说你可以把脚本放到HTML最后或者在Tag Manager中在DomContentLoaded之后触发。

选择DOM Ready触发器
选择DOM Ready触发器

相对于这样:

document.addEventListener('DOMContentLoaded', function() {
    //Put your code here if the JS is in the head of your html
});

说到这里,有的读者要问了。那我们还是无法产生一个click事件啊?我们依然无法知道用户是否在菜单中选择的是打开页面还是复制等操作。

的确如此,因为浏览器的安全原因,你无法获得用户在菜单上的行为信息。访问的来源页面无法获得点击信息。仅有目的地页面可知。所以便有了第二种思路。

第二种思路在于让右键链接失效。那代码更简单,直接禁用右键菜单即可。

// Get all link elements with a specific href
var links = document.querySelectorAll('a[href="https://maxket.com/"]');

// Add event listener for the contextmenu event to each link
links.forEach(function(link) {
  link.addEventListener('contextmenu', function(e) {
     e.preventDefault();
  });
});

有的小伙伴又要说了。如何才能保留这个右键菜单呢?我们可以使用JS链接,而不是标准的<a>链接。

<!DOCTYPE html>
<html lang="zh">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>JavaScript Link Example</title>
  <script>
    function linkClick() {
      window.location.href = "https://maxket.com/";
    }
  </script>
</head>
<body>
  <a href="javascript:linkClick();">极诣数字营销</a>
</body>
</html>

上面代码提供了一个JS链接的示范。因为href中并非URL,所以右键打开并不会成功。用户只能通过左键打开链接,你可以在linkClick方法中加入你想要的事件。

用JS链接的方法不适合大范围使用,因为它不是正常的链接,不利于SEO。但起码我们不用在链接上禁用右键菜单了。

上面是马老师给出的三种方法,各有利弊。你有更好的方法吗?欢迎反馈。下面可以测试三种不同的链接。

效果一,链接加参数。

效果二,禁用右键菜单。

效果三,JavaScript链接。

类似文章