How to track users with JS

How to track users with JS

1. Synchronous AJAX

A common way to send data back to the server is to put the collected user data in the unload event and send it back to the server using an AJAX request.

However, asynchronous AJAX may not succeed in the unload event, because the webpage is already unloading and the browser may or may not send it. Therefore, we need to change to synchronous AJAX request.

window.addEventListener('unload', function (event) {
  let xhr = new XMLHttpRequest();
  xhr.open('post', '/log', false);
  xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
  xhr.send('foo=bar');
});

In the above code, the third parameter of the xhr.open() method is false, indicating a synchronous request.

The biggest problem with this approach is that browsers will gradually not allow the use of synchronous AJAX on the main thread. Therefore, the above code does not actually work.

2. Asynchronous AJAX

Asynchronous AJAX actually works. The premise is that there must be some time-consuming synchronization operations in the unload event. This will allow enough time for the asynchronous AJAX to be sent successfully.

function log() {
  let xhr = new XMLHttpRequest();
  xhr.open('post', '/log', true);
  xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
  xhr.send('foo=bar');
}

window.addEventListener('unload', function(event) {
  log();

  // a time-consuming operation
  for (let i = 1; i < 10000; i++) {
    for (let m = 1; m < 10000; m++) { continue; }
  }
});

In the above code, a double loop is forced to execute, which prolongs the execution time of the unload event and causes the asynchronous AJAX to be sent successfully.

3. Tracking User Clicks

setTimeout can also delay page unloading to ensure that the asynchronous request is sent successfully. Below is an example that tracks user clicks.

// The HTML code is as follows // <a id="target" href="https://baidu.com" rel="external nofollow" rel="external nofollow" rel="external nofollow" >click</a>
const clickTime = 350;
const theLink = document.getElementById('target');

function log() {
  let xhr = new XMLHttpRequest();
  xhr.open('post', '/log', true);
  xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
  xhr.send('foo=bar');
}

theLink.addEventListener('click', function (event) {
  event.preventDefault();
  log();

  setTimeout(function () {
    window.location.href = theLink.getAttribute('href');
  }, clickTime);
});

The above code uses setTimeout to delay the page redirect for 350 milliseconds, thus giving the asynchronous AJAX time to send out.

4. Rebound Tracking

Track user clicks and use bounce tracking.

The so-called "bounce tracking" means that when a web page jumps, it first jumps to one or more intermediate URLs to collect information, and then jumps to the original target URL.

// The HTML code is as follows // <a id="target" href="https://baidu.com" rel="external nofollow" rel="external nofollow" rel="external nofollow" >click</a>
const theLink = document.getElementById('target');

theLink.addEventListener('click', function (event) {
  event.preventDefault();
  window.location.href = '/jump?url=' + 
    encodeURIComponent(theLink.getAttribute('href'));
});

In the above code, when the user clicks, it will be forced to jump to an intermediate URL, carry the information over, and after processing, jump to the original target URL.

Google and Baidu are doing this now. When you click on the search results, it will bounce multiple times before jumping to the target URL.

5. Beacon API

The above practices will delay the uninstallation of web pages and seriously affect the user experience.

In order to solve the problem that asynchronous requests cannot succeed when the web page is unloaded, the browser has specially implemented a Beacon API, which allows asynchronous requests to be separated from the current main thread and sent in the browser process, so that it can be guaranteed to be sent.

window.addEventListener('unload', function (event) {
  navigator.sendBeacon('/log', 'foo=bar');
});

In the above code, the navigator.sendBeacon() method ensures that the asynchronous request will be sent. The first parameter is the URL to request, and the second parameter is the data to send.

Note that the Beacon API issues a POST request.

6. Ping properties

The HTML <a> tag has a ping attribute. As long as the user clicks it, a POST request will be sent to the URL specified by the attribute.

<a href="https://baidu.com" rel="external nofollow" rel="external nofollow" rel="external nofollow" ping="/log?foo=bar">
  click
</a>

In the above code, when the user clicks the jump button, a POST request will be sent to the URL /log.

The ping attribute cannot specify a data body, and it seems that the information can only be carried through the query string of the URL.

The above is the details of how to track users with JS. For more information about tracking users with JS, please pay attention to other related articles on 123WORDPRESS.COM!

You may also be interested in:
  • JS Asynchronous Stack Tracing: Why await is better than Promise
  • Java dynamic tracing technology research from JSP to Arthas
  • Detailed explanation of tracking algorithm examples of commonly used algorithms in JS/HTML5 games
  • Detailed explanation of VueJS data-driven and dependency tracking analysis
  • JavaScript Error Handling and Stack Tracing Explained
  • Using Raygun to automatically track exceptions in AngularJS
  • JS script to achieve automatic click-through on web pages
  • Detailed explanation of the basic syntax based on JS scripting language
  • js script to write a simple voting system

<<:  Solution to 700% CPU usage of Linux process that cannot be killed

>>:  Detailed explanation of installing applications in Linux Centos7 without Internet connection

Recommend

Detailed explanation of the data responsiveness principle of Vue

This article is mainly for those who do not under...

Example verification MySQL | update field with the same value will record binlog

1. Introduction A few days ago, a development col...

Example of how to set automatic creation time and modification time in mysql

This article describes how to set the automatic c...

Basic steps to use Mysql SSH tunnel connection

Preface For security reasons, the root user of My...

What is ssh? How to use? What are the misunderstandings?

Table of contents Preface What is ssh What is ssh...

In-depth understanding of umask in new linux file permission settings

Preface The origin is a question 1: If your umask...

Example of how to check the capacity of MySQL database table

This article introduces the command statements fo...

Summary of the differences between Html, sHtml and XHtml

For example: <u> This has no ending characte...

How to display JSON data in HTML

background: Sometimes we need to display json dat...

How to build lnmp environment in docker

Create a project directory mkdir php Create the f...