DEV Community

Peter Thaleikis 🍪
Peter Thaleikis 🍪

Posted on • Originally published at on

How to check Do Not Track (DNT) in JavaScript?

What is Do Not Track?

Do not track is a user preference to not being tracked by Google Analytics or similar services. If active, it is sent as an HTTP header with all requests going out to servers. Depending on the browser you are using this is switched on by default in private/incognito sessions.

How to check if DNT is set using JavaScript?

In some cases, you might need to find out if DNT is active on the fly when someone is visiting your website. This could, for example, be the case if you are using a static site generator and need to compile the GA code in, but only activate it if your website visitor is fine with it. The following code snippet allows you to check if DNT is set using JavaScript:

let dntActive = () => {
  // get the value from the various browser implementations.
  let dnt_active = parseInt(
    // Internet Explorer 9 and 10 vendor prefix
    navigator.msDoNotTrack ||

    // IE 11 uses window.doNotTrack
    window.doNotTrack ||

    // W3C

  // If this comes to exactly 1 DNT is set.
  return (dnt_active === 1);

// Check if DNT is active.
if (dntActive()) {
  // active
} else {
  // inactive

Following this example, you should find out if a user doesn't like to be tracked.

This quick tip was inspired by 🙏️

Top comments (0)