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

Correct way to load fonts in Vue.js

Table of contents Declare fonts with font-face co...

js array fill() filling method

Table of contents 1. fill() syntax 2. Use of fill...

How to sort a row or column in mysql

method: By desc: Neither can be achieved: Method ...

Summary of Common Problems with Mysql Indexes

Q1: What indexes does the database have? What are...

In-depth explanation of the locking mechanism in MySQL

Preface In order to ensure the consistency and in...

Keepalived implements Nginx load balancing and high availability sample code

Chapter 1: Introduction to keepalived The purpose...

Detailed tutorial on configuring local yum source in CentOS8

The centos8 distribution is released through the ...

SQL merge operation of query results of tables with different columns

To query two different tables, you need to merge ...

Example code for css3 to achieve scroll bar beautification effect

The specific code is as follows: /*Scroll bar wid...

Detailed explanation of global parameter persistence in MySQL 8 new features

Table of contents Preface Global parameter persis...

What to do if the container started by docker run hangs and loses data

Scenario Description In a certain system, the fun...