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
navigator.doNotTrack,
10
);
// 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 https://github.com/saberland/saber/blob/master/packages/saber-plugin-google-analytics/saber-browser.js ποΈ
Top comments (0)