diff --git a/_test/action_plugin_googletagmanagerTest.php b/_test/action_plugin_googletagmanagerTest.php index d983e2d..e24da12 100644 --- a/_test/action_plugin_googletagmanagerTest.php +++ b/_test/action_plugin_googletagmanagerTest.php @@ -44,6 +44,7 @@ public function test_google_tag_manager() $value = $domElement->textContent; } else { // iframe src as subelement of noscript + $this->assertEquals("iframe", $domElement->firstChild->nodeName); $value = $domElement->firstChild->getAttribute("src"); } $patternFound = preg_match("!https://www.googletagmanager.com/.*id=.*$gtmValue!s", $value) === 1; diff --git a/action.php b/action.php index 0e19978..864364e 100644 --- a/action.php +++ b/action.php @@ -17,30 +17,36 @@ public function register(EventHandler $controller) public function addHeaders(&$event, $param) { - $GTMID = $this->getConf(self::GTMID); - if (!$GTMID) return; + $GTMID = $this->getConf(self::GTMID); + if (!$GTMID) return; - $is_AW_tag = substr($GTMID, 0, 3) == 'AW-'; + $is_AW_tag = substr($GTMID, 0, 3) == 'AW-'; if ($is_AW_tag) { - $event->data['script'][] = ['src' => "https://www.googletagmanager.com/gtag/js?id=" . $GTMID]; - $event->data['script'][] = ['type' => 'text/javascript', - '_data' => "window.dataLayer = window.dataLayer || []; function gtag(){dataLayer.push(arguments);}" . - " gtag('js', new Date()); gtag('config', '" . - $GTMID . - "');"]; + $script1 = "https://www.googletagmanager.com/gtag/js?id={$GTMID}"; + $script2 = <<data['script'][] = ['src' => $script1]; + $event->data['script'][] = ['type' => 'text/javascript', '_data' => $script2]; } else { - $event->data['noscript'][] = ['_data' => '']; - $event->data['script'][] = ['type' => 'text/javascript', - '_data' => "(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); -})(window,document,'script','dataLayer','" . - $GTMID . - "');"]; + $iframe = << + EOT; + + $script = <<data['noscript'][] = ['_data' => $iframe]; + $event->data['script'][] = ['type' => 'text/javascript', '_data' => $script]; } } } diff --git a/plugin.info.txt b/plugin.info.txt index 7e7e456..f541dff 100644 --- a/plugin.info.txt +++ b/plugin.info.txt @@ -1,7 +1,7 @@ base googletagmanager author Alexander Lehmann email alexlehm@gmail.com -date 2026-01-04 +date 2026-01-06 name Google Tag Manager desc Integrate a GTM tag into the wiki url https://wiki.lehmann.cx/projects:dokuwiki_gtm