Skip to content

Commit

Permalink
feat: add ability to provide a nonce to inline script for csp
Browse files Browse the repository at this point in the history
  • Loading branch information
wilr committed Jan 13, 2023
1 parent 8736e18 commit 5b0a8dd
Show file tree
Hide file tree
Showing 2 changed files with 31 additions and 5 deletions.
21 changes: 19 additions & 2 deletions src/GoogleAnalyticsProvider.php
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,8 @@

namespace Heyday\Analytics;

use SilverStripe\Control\Controller;

/**
* Class GoogleAnalyticsProvider
* @package Heyday\Analytics
Expand All @@ -17,8 +19,23 @@ class GoogleAnalyticsProvider extends AnalyticsProvider
public function getAnalyticsCode()
{
$id = $this->getAnalyticsID();
if (!$id) {
return '';
}

$scriptTag = 'script';

// support nonce on scripts
$controller = Controller::curr();

if ($controller && $controller->hasMethod('getNonce')) {
$nonce = $controller->getNonce();
$scriptTag = "script nonce=\"$nonce\"";
}


$analyticsCode = <<<EOS
<script>
<$scriptTag>
(function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){
(i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o),
m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m)
Expand All @@ -31,4 +48,4 @@ public function getAnalyticsCode()
return $analyticsCode;
}

}
}
15 changes: 12 additions & 3 deletions src/GoogleTagManagerProvider.php
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,8 @@

namespace Heyday\Analytics;

use SilverStripe\Control\Controller;

/**
* Class GoogleTagManagerProvider
* @package Heyday\Analytics
Expand All @@ -22,13 +24,20 @@ public function getAnalyticsCode(): string
{
$id = $this->getAnalyticsID();

if (!$id) {
return '';

$scriptTag = 'script';

// support nonce on scripts
$controller = Controller::curr();

if ($controller && $controller->hasMethod('getNonce')) {
$nonce = $controller->getNonce();
$scriptTag = "script nonce=\"$nonce\"";
}

$analyticsCode = <<< EOS
<!-- Google Tag Manager -->
<script>(function(w,d,s,l,i){w[l]=w[l]||[];w[l].push({'gtm.start':
<$scriptTag>(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'?'&l='+l:'';j.async=true;j.src=
'https://www.googletagmanager.com/gtm.js?id='+i+dl;f.parentNode.insertBefore(j,f);
Expand Down

0 comments on commit 5b0a8dd

Please sign in to comment.