From 5b0a8dd95f0be2170aeceea72c44d1d23d60ce96 Mon Sep 17 00:00:00 2001 From: Will Rossiter Date: Fri, 13 Jan 2023 13:52:47 +1300 Subject: [PATCH] feat: add ability to provide a nonce to inline script for csp --- src/GoogleAnalyticsProvider.php | 21 +++++++++++++++++++-- src/GoogleTagManagerProvider.php | 15 ++++++++++++--- 2 files changed, 31 insertions(+), 5 deletions(-) diff --git a/src/GoogleAnalyticsProvider.php b/src/GoogleAnalyticsProvider.php index 19c6e97..846b35c 100755 --- a/src/GoogleAnalyticsProvider.php +++ b/src/GoogleAnalyticsProvider.php @@ -2,6 +2,8 @@ namespace Heyday\Analytics; +use SilverStripe\Control\Controller; + /** * Class GoogleAnalyticsProvider * @package Heyday\Analytics @@ -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 = << + <$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) @@ -31,4 +48,4 @@ public function getAnalyticsCode() return $analyticsCode; } -} \ No newline at end of file +} diff --git a/src/GoogleTagManagerProvider.php b/src/GoogleTagManagerProvider.php index 7b7723c..c2872b2 100755 --- a/src/GoogleTagManagerProvider.php +++ b/src/GoogleTagManagerProvider.php @@ -2,6 +2,8 @@ namespace Heyday\Analytics; +use SilverStripe\Control\Controller; + /** * Class GoogleTagManagerProvider * @package Heyday\Analytics @@ -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 -