Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add support for Google Analitics global site tag #1495

Open
wants to merge 4 commits into
base: main
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
39 changes: 28 additions & 11 deletions libs/plugins/google-analytics/src/lib/plugins-google-analytics.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { registerPlugin, getMyConfig } from '@scullyio/scully';
import { getMyConfig, registerPlugin } from '@scullyio/scully';

export const GoogleAnalytics = 'googleAnalytics';

Expand All @@ -8,22 +8,39 @@ export const googleAnalyticsPlugin = async (html: string): Promise<string> => {
if (!googleAnalyticsConfig) {
throw new Error('googleAnalytics plugin missing Global Site Tag');
}
const siteTag: string = googleAnalyticsConfig['globalSiteTag'];

const googleAnalyticsScript = `
const googleAnalyticsScript = getSnippet(googleAnalyticsConfig['globalSiteTag']);

return html.replace(/<\/head/i, `${googleAnalyticsScript}</head`);
};

const validator = async () => [];

registerPlugin('postProcessByHtml', GoogleAnalytics, googleAnalyticsPlugin, validator);

function getSnippet(siteTag: string) {
if (siteTag.startsWith('G-')) {
return `
<!-- Global site tag (gtag.js) - Google Analytics -->
<script async src="https://www.googletagmanager.com/gtag/js?id=${siteTag}"></script>
<script>
window.dataLayer = window.dataLayer || [];
function gtag(){dataLayer.push(arguments);}
gtag('js', new Date());

gtag('config', '${siteTag}');
</script>
`;
}

return `
<!-- Google Analytics -->
<script sk>
window.ga=window.ga||function(){(ga.q=ga.q||[]).push(arguments)};ga.l=+new Date;
ga('create', '${siteTag}', 'auto');
ga('send', 'pageview');
</script>
<script sk async src='https://www.google-analytics.com/analytics.js'></script>
<!-- End Google Analytics -->
<!-- End Google Analytics -->
`;

return html.replace(/<\/head/i, `${googleAnalyticsScript}</head`);
};

const validator = async () => [];

registerPlugin('postProcessByHtml', GoogleAnalytics, googleAnalyticsPlugin, validator);
}