Commit c8f3da39 authored by Laurent Sittler's avatar Laurent Sittler ©

feat(Google): add Goole Analytics

- Add custom action schema
- Add PowerShell script installation
- Add documentation
- Update main readme
parent 7ab044e1
...@@ -36,4 +36,16 @@ Provide a custom script to set up easily (without any more code) Matomo Analytic ...@@ -36,4 +36,16 @@ Provide a custom script to set up easily (without any more code) Matomo Analytic
Provide a custom script to set up easily (without any more code) Matomo Tag Manager on SharePoint site collections with classic experience. Provide a custom script to set up easily (without any more code) Matomo Tag Manager on SharePoint site collections with classic experience.
[Learn more ›](SharePoint.MTM) [Learn more ›](SharePoint.MTM)
\ No newline at end of file
### SharePoint.GA
Provide a custom script to set up easily (without any more code) Google Analytics on SharePoint site collections with classic experience.
[Learn more ›](SharePoint.GA)
### SharePoint.GTM
Provide a custom script to set up easily (without any more code) Google Tag Manager on SharePoint site collections with classic experience.
[Learn more ›](SharePoint.GTM)
\ No newline at end of file
<?xml version="1.0"?>
<pnp:Provisioning xmlns:pnp="http://schemas.dev.office.com/PnP/2015/12/ProvisioningSchema">
<pnp:Preferences Generator="OfficeDevPnP.Core, Version=2.1.1602.1, Culture=neutral, PublicKeyToken=3751622786b357c2">
<pnp:Parameters>
<pnp:Parameter Key="trackingSiteId"></pnp:Parameter>
<pnp:Parameter Key="trackUserId"></pnp:Parameter>
</pnp:Parameters>
</pnp:Preferences>
<pnp:Templates ID="CONTAINER-SP-GOOGLE-ANALYTICS">
<pnp:ProvisioningTemplate ID="SP-GOOGLE-ANALYTICS">
<pnp:CustomActions>
<pnp:SiteCustomActions>
<pnp:CustomAction Name="SPGoogleAnalytics"
Location="ScriptLink"
Sequence="0"
ScriptBlock="
var headID = document.getElementsByTagName('head')[0];
var scripts = document.getElementsByTagName('script');
var scriptsSrc = [];
for (var i = 0; i &lt; scripts.length; i++) {
if (scripts[i].type === 'text/javascript') {
if (scripts[i].id) {
scriptsSrc.push(scripts[i].id);
}
}
}
if (scriptsSrc.indexOf('SPGoogleAnalytics') === -1) {
var srcScript = document.createElement('script');
srcScript.type = 'text/javascript';
srcScript.async = true;
srcScript.src = 'https://www.googletagmanager.com/gtag/js?id={parameter:trackingSiteId}';
headID.appendChild(srcScript);
var newScript = document.createElement('script');
newScript.id = 'SPGoogleAnalytics';
newScript.type = 'text/javascript';
newScript.text = `
window.dataLayer = window.dataLayer || [];
function gtag(){dataLayer.push(arguments);}
gtag('js', new Date());
{parameter:trackUserId}
gtag('config', '{parameter:trackingSiteId}');
`;
headID.appendChild(newScript);
scriptsSrc.push('SPGoogleAnalytics');
}" />
</pnp:SiteCustomActions>
</pnp:CustomActions>
</pnp:ProvisioningTemplate>
</pnp:Templates>
</pnp:Provisioning>
\ No newline at end of file
This diff is collapsed.
'use strict';
/**
* Google Analytics
* @namespace
*/
var GoogleAnalytics = GoogleAnalytics || {};
if (window.hasOwnProperty('Type')) {
Type.registerNamespace('StickyFooter');
} else {
window.StickyFooter = window.StickyFooter || {};
}
/**
* Google Analytics Main
* @class
*/
GoogleAnalytics.Main = (function () {
return {
/**
* Init Google Analytics
* @public
*/
init: function () {
}
};
})();
GoogleAnalytics.Main.init();
<#
.SYNOPSIS
Enables Google Analytics on a target classic SharePoint site collection.
.EXAMPLE
PS C:\> .\SPGA.ps1 -siteUrl "https://intranet.mydomain.com/sites/targetSite" -trackingSiteId "UA-00000000-1"
.EXAMPLE
PS C:\> $creds = Get-Credential
PS C:\> .\SPGA.ps1 -siteUrl "https://intranet.mydomain.com/sites/targetSite" -trackingSiteId "UA-00000000-1" -Credentials $creds
.NOTES
Version : 1.0.0.0
File Name : SPGA.ps1
Author : Laurent Sittler - [email protected]
.LINK
https://gitlab.lsonline.fr/SharePoint/javascript-customactions
#>
[CmdletBinding()]
param
(
[Parameter(Mandatory = $true, HelpMessage="Enter the URL of the target site collection, e.g. 'https://intranet.mydomain.com/sites/targetSite'")]
[String]$siteUrl,
[Parameter(Mandatory = $true, HelpMessage="Google Analytics Tracking Site ID, e.g. '1'")]
[String]$trackingSiteId,
[Parameter(Mandatory = $false, HelpMessage="Accurately measure your unique users based on their login name. Default 'false'")]
[string]$trackUserId,
[Parameter(Mandatory = $false, HelpMessage="Optional administration credentials")]
[PSCredential]$Credentials
)
If ($Credentials -eq $null)
{
$Credentials = Get-Credential -Message "Enter Admin Credentials"
}
Write-Host -ForegroundColor White "--------------------------------------------------------"
Write-Host -ForegroundColor White "| Enabling Google Analytics |"
Write-Host -ForegroundColor White "--------------------------------------------------------"
Write-Host
try
{
Write-Host -ForegroundColor Yellow "Connecting to target site URL: $siteUrl"
Connect-PnPOnline $siteUrl -Credentials $Credentials
Write-Host -ForegroundColor Yellow "Enabling Google Analytics to the target site"
# Init additional parameters
$uidScript = ""
# If track user id is true, then set 'setUserId' var content
If ($trackUserId) {
$uidScript = "gtag('set', {'user_id': _spPageContextInfo.userLoginName });";
}
# PnP Parameters used by the XML Template
$pnpParams = @{
"trackingSiteId" = $trackingSiteId;
"trackUserId" = $uidScript;
}
# Retrieve all current CustomAction and remove old Google Analytics first
Get-PnPCustomAction -Scope site | ForEach-Object {
If ($_.Name -eq "SPGoogleAnalytics") {
Write-Host -ForegroundColor Yellow "Remove old Google Analytics Custom Action from target site"
Remove-PnPCustomAction -Identity $_.Id -scope site -Force -Confirm:$false
}
}
# Apply PnP Template = create custom action script
Write-Host -ForegroundColor Yellow "Apply PnP schema to target site"
Apply-PnPProvisioningTemplate -Path .\GoogleAnalytics.xml -Parameters $pnpParams -Handlers CustomAction
Write-Host -ForegroundColor Green "Google Analytics implementation succeeded"
}
catch
{
Write-Host -ForegroundColor Red "Exception occurred!"
Write-Host -ForegroundColor Red "Exception Type: $($_.Exception.GetType().FullName)"
Write-Host -ForegroundColor Red "Exception Message: $($_.Exception.Message)"
}
\ No newline at end of file
<?xml version="1.0"?>
<pnp:Provisioning xmlns:pnp="http://schemas.dev.office.com/PnP/2015/12/ProvisioningSchema">
<pnp:Preferences Generator="OfficeDevPnP.Core, Version=2.1.1602.1, Culture=neutral, PublicKeyToken=3751622786b357c2">
<pnp:Parameters>
<pnp:Parameter Key="containerID"></pnp:Parameter>
</pnp:Parameters>
</pnp:Preferences>
<pnp:Templates ID="CONTAINER-SP-GOOGLE-TAGMANAGER">
<pnp:ProvisioningTemplate ID="SP-GOOGLE-TAGMANAGER">
<pnp:CustomActions>
<pnp:SiteCustomActions>
<pnp:CustomAction Name="SPGoogleTagManager"
Location="ScriptLink"
Sequence="0"
ScriptBlock="
var headID = document.getElementsByTagName('head')[0];
var scripts = document.getElementsByTagName('script');
var scriptsSrc = [];
for (var i = 0; i &lt; scripts.length; i++) {
if (scripts[i].type === 'text/javascript') {
if (scripts[i].id) {
scriptsSrc.push(scripts[i].id);
}
}
}
if (scriptsSrc.indexOf('SPGoogleTagManager') === -1) {
(function(w,d,s,l,i){w[l]=w[l]||[];w[l].push({'gtm.start':
new Date().getTime(),event:'gtm.js'});var f=d.getElementsByTagName(s)[0],
j=d.createElement(s),dl=l!='dataLayer'?'&amp;l='+l:'';j.id='SPGoogleTagManager';j.async=true;j.src=
'https://www.googletagmanager.com/gtm.js?id='+i+dl;f.parentNode.insertBefore(j,f);
})(window,document,'script','dataLayer','{parameter:containerID}');
scriptsSrc.push('SPGoogleTagManager');
}" />
</pnp:SiteCustomActions>
</pnp:CustomActions>
</pnp:ProvisioningTemplate>
</pnp:Templates>
</pnp:Provisioning>
\ No newline at end of file
## Google Tag Manager for SharePoint 2013/2016/2019/Online
This solution demonstrates how to implement Google Tag Manager in Microsoft SharePoint 2013/2016/2019 On-Premises or SharePoint Online using the PowerShell script SPGTM.ps1, and also provides you the capability to enable a Tag Management System for a Site Collection.
### Setup Instructions
In order to set the solution up on a target Site Collection, you simply need to:
* [Download the files included in this solution](#download)
* [Setup software requirements](#requirements)
* [Execute the *SPGTM* script](#execute)
>**Note**: If you are using SharePoint 2013 environment, setup scripts are assuming that you are running at least the April 2015 CU.
<a name="download"></a>
#### Download the files
You can download the files manually, one by one, or you can download as ZIP the repository with all custom actions. Within the ZIP archive, under the `/SharePoint.GTM` folder, you will find all the required files.
<a name="requirements"></a>
#### Setup software requirements
This solution requires the SharePointPnP.PowerShell commands, which you can install from one of the following link, depending on your target platform:
(see the [SharePointPnP.PowerShell installation instructions](https://github.com/OfficeDev/PnP-PowerShell#installation) for further details):
* [SharePointPnP.PowerShell package for SharePoint 2013](https://github.com/SharePoint/PnP-PowerShell/releases)
* [SharePointPnP.PowerShell package for SharePoint 2016](https://github.com/SharePoint/PnP-PowerShell/releases)
* [SharePointPnP.PowerShell package for SharePoint Online](https://github.com/SharePoint/PnP-PowerShell/releases)
>**Note**: Depending on your target platform (SharePoint 2013/2016/2019 On-Premises or SharePoint Online) you should refer to
the right build of the SharePointPnP.PowerShell commands. Nevertheless, even the SharePointPnPPowerShellOnline version, which
targets SharePoint Online, is viable to setup this solution on-premises. If you are running SharePoint 2013 environment,
PowerShell cmdlets used by the automation scripts have dependency on April 2015 CU to be installed on server side.
<a name="execute"></a>
#### Execute the *SPGTM* script
Once you have installed the SharePointPnP.PowerShell commands, you can open a PowerShell console, go to the path where you stored the files and execute the *SPGTM.ps1* script.
The *SPGTM* script accepts the following parameters:
| Parameter | Required | Default value | Description |
|-----------|----------|---------------|-------------|
| `-siteUrl` | yes | `undefined` | URL of the site to provision and/or enable the custom action |
| `-containerID` | yes | `undefined` | Google Tag Manager container ID |
| `-Credentials` | no | `undefined` | User credentials that will be used to authenticate against both the target Site Collection. Should be the credentials of a user, who is Site Collection Administrator for the target Site Collections. If you don't provide this parameter, the script will directly prompt you for credentials. |
You can here see a couple of examples about how to invoke the *SPGTM* script:
##### EXAMPLE 1
> Change container ID in accordance with your environment.
```PowerShell
PS C:\> .\SPGTM.ps1 -siteUrl "https://intranet.mydomain.com/sites/targetSite" -containerID "GTM-1234567"
```
The example above enables the Google Tag Manager on the target Site Collection with URL https://intranet.mydomain.com/sites/targetSite.
The user's credentials are not provided, the script will therefore directly prompt the user.
##### EXAMPLE 2
> Change container ID in accordance with your environment.
```PowerShell
PS C:\> $creds = Get-Credential
PS C:\> .\SPGTM.ps1 -siteUrl "https://intranet.mydomain.com/sites/targetSite" -containerID "GTM-1234567" -Credentials $creds
```
The example above enables the Google Tag Manager on the target Site Collection with the user's credentials provided through the *$creds* variable.
\ No newline at end of file
<#
.SYNOPSIS
Enables Google Tag Manager on a target classic SharePoint site collection.
.EXAMPLE
PS C:\> .\SPGTM.ps1 -siteUrl "https://intranet.mydomain.com/sites/targetSite" -containerID "GTM-1234567"
.EXAMPLE
PS C:\> $creds = Get-Credential
PS C:\> .\SPGTM.ps1 -siteUrl "https://intranet.mydomain.com/sites/targetSite" -containerID "GTM-1234567" -Credentials $creds
.NOTES
Version : 1.0.0.0
File Name : SPGTM.ps1
Author : Laurent Sittler - [email protected]
.LINK
https://gitlab.lsonline.fr/SharePoint/javascript-customactions
#>
[CmdletBinding()]
param
(
[Parameter(Mandatory = $true, HelpMessage="Enter the URL of the target site collection, e.g. 'https://intranet.mydomain.com/sites/targetSite'")]
[String]$siteUrl,
[Parameter(Mandatory = $true, HelpMessage="Google Tag Manager container ID, e.g. 'GTM-1234567'")]
[String]$containerID,
[Parameter(Mandatory = $false, HelpMessage="Optional administration credentials")]
[PSCredential]$Credentials
)
If ($Credentials -eq $null)
{
$Credentials = Get-Credential -Message "Enter Admin Credentials"
}
Write-Host -ForegroundColor White "--------------------------------------------------------"
Write-Host -ForegroundColor White "| Enabling Google Tag Manager |"
Write-Host -ForegroundColor White "--------------------------------------------------------"
Write-Host
try
{
Write-Host -ForegroundColor Yellow "Connecting to target site URL: $siteUrl"
Connect-PnPOnline $siteUrl -Credentials $Credentials
Write-Host -ForegroundColor Yellow "Enabling Google Tag Manager to the target site"
# PnP Parameters used by the XML Template
$pnpParams = @{
"containerID" = $containerID;
}
# Retrieve all current CustomAction and remove old Google Tag Manager first
Get-PnPCustomAction -Scope site | ForEach-Object {
If ($_.Name -eq "SPGoogleTagManager") {
Write-Host -ForegroundColor Yellow "Remove old Google Tag Manager Custom Action from target site"
Remove-PnPCustomAction -Identity $_.Id -scope site -Force -Confirm:$false
}
}
# Apply PnP Template = create custom action script
Write-Host -ForegroundColor Yellow "Apply PnP schema to target site"
Apply-PnPProvisioningTemplate -Path .\GoogleTagManager.xml -Parameters $pnpParams -Handlers CustomAction
Write-Host -ForegroundColor Green "Google Tag Manager implementation succeeded"
}
catch
{
Write-Host -ForegroundColor Red "Exception occurred!"
Write-Host -ForegroundColor Red "Exception Type: $($_.Exception.GetType().FullName)"
Write-Host -ForegroundColor Red "Exception Message: $($_.Exception.Message)"
}
\ No newline at end of file
...@@ -67,7 +67,7 @@ The user's credentials are not provided, the script will therefore directly prom ...@@ -67,7 +67,7 @@ The user's credentials are not provided, the script will therefore directly prom
```PowerShell ```PowerShell
PS C:\> $creds = Get-Credential PS C:\> $creds = Get-Credential
PS C:\> .\SPMTM.ps1 -siteUrl "https://intranet.mydomain.com/sites/targetSite" -trackingUrl -trackingUrl https://matomo.my-domain.com/js/container_[contrainer ID].js -Credentials $creds PS C:\> .\SPMTM.ps1 -siteUrl "https://intranet.mydomain.com/sites/targetSite" -trackingUrl https://matomo.my-domain.com/js/container_[contrainer ID].js -Credentials $creds
``` ```
The example above enables the Matomo Tag Manager on the target Site Collection with the user's credentials provided through the *$creds* variable. The example above enables the Matomo Tag Manager on the target Site Collection with the user's credentials provided through the *$creds* variable.
\ No newline at end of file
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment