Last active
November 6, 2023 10:00
-
-
Save maxboeck/7130cf69bfe2517e148288724f7877ce to your computer and use it in GitHub Desktop.
Check "Do Not Track" Client Hint
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 | |
} |
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
awesome, thanks!