Skip to content

Commit

Permalink
feat(app): prevent Google Analytics script loading when opt-out
Browse files Browse the repository at this point in the history
  • Loading branch information
kubosho committed Jul 17, 2024
1 parent 8b89c37 commit d8e1361
Show file tree
Hide file tree
Showing 2 changed files with 17 additions and 12 deletions.
25 changes: 15 additions & 10 deletions src/app/components/ExternalResourceLink.astro
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,6 @@
import { pathList } from '../../../constants/path_list';
import { FAVICON_URL } from '../../../constants/site_data';
import { retrieveTranslation } from '../locales/i18n';
import { GTM_URL } from '../tracking/gtm_data';
interface Props {
canonicalUrl: string;
Expand All @@ -18,17 +17,23 @@ const webSiteTitle = retrieveTranslation('website.title');
<link rel="icon" type="image/png" href={FAVICON_URL} />
<link rel="alternate" type="application/atom+xml" href={pathList.feed} title={webSiteTitle} />
<link rel="preload" as="style" href="/assets/styles/color_scheme.css" />
<link rel="preload" as="script" href={GTM_URL} />
<link rel="stylesheet" href="/assets/styles/foundation.css" />
<link rel="stylesheet" href="/assets/styles/variables.css" />
<link rel="stylesheet" href="/assets/styles/main.css" />
<script src={GTM_URL} defer></script>
<script is:inline>
if (window.localStorage.getItem('ga:optoutId') === null) {
window.dataLayer = [];
window.dataLayer.push({
'gtm.start': Date.now(),
event: 'gtm.js',
});

<script>
import { initialDatalayer } from '../tracking/data_layer';
import { GTM_URL } from '../tracking/gtm_data';

const res = await fetch('/policy/optout', { method: 'GET' });
const body = await res.json();

if (!body.enabled) {
const script = document.createElement('script');
script.defer = true;
script.src = GTM_URL;
document.head.appendChild(script);

initialDatalayer();
}
</script>
4 changes: 2 additions & 2 deletions src/app/tracking/data_layer.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ declare global {
}
}

(() => {
export const initialDatalayer = (): void => {
const win = getBrowsingContextWindowProxy();
if (win === null) {
return;
Expand All @@ -17,4 +17,4 @@ declare global {
'gtm.start': Date.now(),
event: 'gtm.js',
});
})();
};

0 comments on commit d8e1361

Please sign in to comment.