Skip to content

Instantly share code, notes, and snippets.

@maxboeck
Last active November 6, 2023 10:00
Show Gist options
  • Save maxboeck/7130cf69bfe2517e148288724f7877ce to your computer and use it in GitHub Desktop.
Save maxboeck/7130cf69bfe2517e148288724f7877ce to your computer and use it in GitHub Desktop.
Check "Do Not Track" Client Hint
const allowsTracking = () => {
const dnt =
window.doNotTrack ||
navigator.doNotTrack ||
navigator.msDoNotTrack
if (dnt === 1 || dnt === '1' || dnt === 'yes') {
return false
}
if ('msTrackingProtectionEnabled' in window.external) {
return !window.external.msTrackingProtectionEnabled()
}
return true
}
if (allowsTracking()) {
// Analytics Tracking Code Here
}
@franciscoandres
Copy link

awesome, thanks!

@astorije
Copy link

astorije commented May 21, 2019

As I was implementing this (thank you!), TypeScript is telling me 2 things:

  • Property 'msDoNotTrack' does not exist on type 'Navigator'. Did you mean 'doNotTrack'?
  • Property 'msTrackingProtectionEnabled' does not exist on type 'never'.

According to https://dev.to/corbindavenport/how-to-correctly-check-for-do-not-track-with-javascript-135d, the former is for IE 10 and older, and the latter is for all versions of IE.

So, for TypeScript, I went with this lame alternative:

interface MSNavigator extends Navigator {
  msDoNotTrack: Navigator['doNotTrack'];
}

interface MSExternal extends External {
  msTrackingProtectionEnabled(): boolean;
}

function isMSExternal(external: External): external is MSExternal {
  return 'msTrackingProtectionEnabled' in external;
}

export const allowsTracking = () => {
  const dnt =
    window.doNotTrack ||
    navigator.doNotTrack ||
    // Support for IE 10 and older
    (navigator as MSNavigator).msDoNotTrack;

  if (dnt === '1' || dnt === 'yes') {
    return false;
  }

  // All versions of IE
  if (window.external && isMSExternal(window.external)) {
    return !window.external.msTrackingProtectionEnabled();
  }

  return true;
};

I would be interested to know if people had more elegant solutions.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment