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 description of component-based front-end development process

Background <br />Students who work on the fr...

Solution to SNMP4J server connection timeout problem

Our network management center serves as the manag...

How to copy MySQL table

Table of contents 1.mysqldump Execution process: ...

How to upload the jar package to nexus via the web page

When using Maven to manage projects, how to uploa...

How to use translate and transition in CSS3

I always feel that translate and transition are v...

Solution to Linux not supporting all commands

What should I do if Linux does not support all co...

Overview of the Differences between Linux TTY/PTS

When we type a letter on the keyboard, how is it ...

Advantages and disadvantages of Table layout and why it is not recommended

Disadvantages of Tables 1. Table takes up more byt...

Detailed explanation of the basic functions and usage of MySQL foreign keys

This article uses examples to illustrate the basi...

CSS realizes div completely centered without setting height

Require The div under the body is vertically cent...

A brief discussion on the binary family of JS

Table of contents Overview Blob Blob in Action Bl...

MySQL Quick Data Comparison Techniques

In MySQL operation and maintenance, a R&D col...