Skip to content

Instantly share code, notes, and snippets.

@dobesv
Created November 30, 2022 05:51
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save dobesv/0dba69925b8975e69b3392da46063db2 to your computer and use it in GitHub Desktop.
Save dobesv/0dba69925b8975e69b3392da46063db2 to your computer and use it in GitHub Desktop.
import { CookiePolicyAcceptance } from './CookiePolicyAcceptance';
import getStoredPolicyAcceptance from './getStoredPolicyAcceptance';
export type DataLayerName = 'dataLayer' | 'ga4DataLayer' | 'adwordsDataLayer';
export type GtagName = 'gtag' | 'adwordsGtag' | 'gtmGtag';
export const gtagFn = (
dataLayerName: DataLayerName,
gtagName: GtagName,
): ((..._args: any[]) => any) =>
window[gtagName] ||
(window[gtagName] = function () {
// eslint-disable-next-line prefer-rest-params
(window[dataLayerName] || (window[dataLayerName] = [])).push(arguments);
});
/**
* Send consent configuration to a google container using gtag. This is used for
* Google Tag Manager, Google Analytics, and Google AdWords to indicate whether they
* can store cookies.
*
* @param dataLayerName Name of the dataLayer global
* @param gtagName Name of the gtag global function
* @param cookiePolicyAcceptance Which cookies the user has accepted. Will be loaded from localStorage if
* not provided as an argument
*/
export default function configureGtagConsent(
dataLayerName: DataLayerName,
gtagName: GtagName,
cookiePolicyAcceptance: CookiePolicyAcceptance = getStoredPolicyAcceptance(),
): void {
const initialCall: boolean = !window[dataLayerName]?.some(
args => args[0] === 'consent',
);
const gtag = gtagFn(dataLayerName, gtagName);
const {
isFunctionalCookiesAccepted,
isPerformanceCookiesAccepted,
isTargetingCookiesAccepted,
} = cookiePolicyAcceptance;
const consent = {
ad_storage: isTargetingCookiesAccepted ? 'granted' : 'denied',
analytics_storage: isPerformanceCookiesAccepted ? 'granted' : 'denied',
functionality_storage: isFunctionalCookiesAccepted ? 'granted' : 'denied',
// We don't have a special category for functionality related cookies, can lump into functional
personalization_storage: isFunctionalCookiesAccepted ? 'granted' : 'denied',
security_storage: 'granted',
};
if (initialCall) {
gtag('consent', 'default', consent);
} else {
gtag('consent', 'update', consent);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment