
In accordance with Google’s guidelines:
Effective from July 1, 2023, standard Universal Analytics properties will cease to process data. This comprehensive guide will assist you in seamlessly incorporating Google Analytics 4 into your SharePoint Sites, enabling you to effectively monitor and analyze your site.
Before we start our development, please ensure the following requirements and has the corresponding versions installed. We will be creating an SPFx Application Customizer to incorporate Google Analytics into your SharePoint Online Site.
Once we got the Google Tag ID, we can now start working on developing our solution
yo @microsoft/sharepoint
What is your solution name? g-4-analytics-sample-webpart
Which type of client-side component to create? Extension
Which type of client-side extension to create? Application Customizer
Add new Application Customizer to solution g-4-analytics-sample-webpart.
What is your Application Customizer name? G4SPFx
Open the solution in Visual Studio Code.
Navigate to ‘\src\extensions\g4SpFx\G4SpFxApplicationCustomizer.ts’ and insert the following code snippet under the ‘onInit’ method
export default class G4SpFxApplicationCustomizerextends BaseApplicationCustomizer<IG4SpFxApplicationCustomizerProperties> {public onInit(): Promise<void> {const trackingID = "G-GSKY9SSX99" // This is my Google Tag ID / Tracking IDconst gtagScript = document.createElement("script"); //We will look for the script element in our html pagegtagScript.type = "text/javascript";gtagScript.src = `//www.googletagmanager.com/gtag/js?id=${trackingID}`;gtagScript.async = true;document.head.appendChild(gtagScript);eval(`window.dataLayer = window.dataLayer || [];function gtag(){dataLayer.push(arguments);}gtag('js', new Date());gtag('config', '${trackingID}')`);return Promise.resolve();}}
For simplicity, I have directly hardcoded my Google Tag ID / Tracking ID. However, it is recommended to place it in the appropriate location, such as the Property Bag of the Site Collection, to monitor the desired site.
gulp serve
To verify that your code is functioning correctly, inspect the page and locate the Google Tag script.