Skip to content

Commit 19f948b

Browse files
committed
Added default gtm script tag if gtm enable
1 parent 61d10bf commit 19f948b

File tree

1 file changed

+32
-1
lines changed

1 file changed

+32
-1
lines changed

src/CookiesManager.php

Lines changed: 32 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,7 @@
22

33
namespace Whitecube\LaravelCookieConsent;
44

5+
use Illuminate\Database\Eloquent\Casts\Json;
56
use Illuminate\Http\Request;
67
use Illuminate\Support\Facades\Cookie as CookieFacade;
78
use Symfony\Component\HttpFoundation\Cookie as CookieComponent;
@@ -198,11 +199,41 @@ protected function getConsentedScripts(bool $withDefault): string
198199

199200
protected function getDefaultScriptTag(): string
200201
{
202+
$gtmScript = config('cookieconsent.google_tag_manager.id') ? $this->getGTMScript() : null;
203+
201204
return '<script '
202205
. 'src="' . route('cookieconsent.script') . '?id='
203206
. md5(\filemtime(LCC_ROOT . '/dist/script.js')) . '" '
204207
. 'defer'
205-
. '></script>';
208+
. '></script>'
209+
. $gtmScript ?? '';
210+
}
211+
212+
/**
213+
* Define default Google Tag Manager script tag;
214+
*/
215+
private function getGTMScript()
216+
{
217+
$defaultSettings = config('cookieconsent.gtm_consent', [
218+
'ad_user_data',
219+
'ad_personalization',
220+
'ad_storage',
221+
'analytics_storage',
222+
]);
223+
224+
$defaultSettings = array_fill_keys($defaultSettings, 'denied');
225+
$defaultSettings['wait_for_update'] = 500;
226+
227+
$defaultJson = json_encode($defaultSettings, JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE);
228+
229+
return '<script type="module" defer>
230+
window.dataLayer = window.dataLayer || []; function gtag() {
231+
dataLayer.push(arguments);
232+
}
233+
234+
gtag(\'consent\', \'default\', ' . $defaultJson . ');
235+
dataLayer.push({\'gtm.start\': new Date().getTime(), \'event\': \'gtm.js\'});
236+
</script> ';
206237
}
207238

208239
/**

0 commit comments

Comments
 (0)