簡體   English   中英

Google Analytics(分析)代碼和帶有php標頭位置的重定向

[英]Google analytics code and redirection with php header location

是否在標題位置重定向之前執行Google Analytics(分析)代碼? 如果沒有,還有其他方法嗎?

例:

<html>
<body>
<script>
  (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)
  })(window,document,'script','//www.google-analytics.com/analytics.js','ga');

  ga('create', 'UA-0000000-0', 'domain.com');
  ga('send', 'pageview');

</script>
</body>
</html>
<?php
header('Location: http://domain.com');
?>

試試看-沒有PHP,(抱歉)沒有任何重定向原因代碼(如“ 301”等)。

就我而言,它可以正常工作:

 <html> <body> <script> (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) })(window,document,'script','//www.google-analytics.com/analytics.js','ga'); ga('create', 'UA-0000000-0', 'domain.com'); ga('send', 'pageview'); window.location = 'http://www.domain.com/redirect-example'; </script> </body> </html> 

我很高興收到任何反饋:-)

<?PHP
ob_start();

echo "<script>
  (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)
  })(window,document,'script','//www.google-analytics.com/analytics.js','ga');

  ga('create', 'UA-0000000-0', 'domain.com');
  ga('send', 'pageview');
</script>";

header("Location: http://www.domain.com/");        
ob_flush();  

考慮一下您要在這里做什么:

Google Analytics(分析)代碼由瀏覽器執行。 PHP是在服務器上生成HTTP響應的預處理器。

因此,執行順序為:

  1. 請求進入(在Apache,NGINX上,無論如何)
  2. PHP獲取請求並執行必要的操作
  3. PHP生成的輸出(通常為HTML)被發送回客戶端
  4. 客戶端的瀏覽器呈現響應
  5. 響應中的任何JavaScript代碼都在客戶端的瀏覽器中運行

PHP將在步驟2中生成HTTP重定向。它告訴客戶端的瀏覽器轉到其他地方,然后從步驟1重新開始。但是您基本上希望步驟5在兩者之間的某個位置執行。

顯然:那是行不通的。

您或者找到了一種從服務器端觸發Google Analytics(分析)的方法(這可能違背了進行跟蹤的目的),或者您只需擺脫重定向(將其替換為JavaScript位置更改)或跳過跟蹤呼叫。

如果您只需要一個下載計數器,則可以在發出重定向之前讓PHP記錄該匹配。 那行得通。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM