【问题标题】:Google analytics code and redirection with php header location带有 php 标头位置的 Google 分析代码和重定向
【发布时间】:2014-03-05 19:54:42
【问题描述】:

是否会在标头位置重定向之前执行 Google 分析代码?如果没有,还有其他方法吗?

例子:

<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');
?>

【问题讨论】:

标签: javascript php google-analytics http-headers


【解决方案1】:

试试 - 没有 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>

我很高兴收到任何反馈 :-)

【讨论】:

  • 这确实提供了一个可能的解决方案,但您没有解释为什么问题中的代码不起作用以及您的解决方案解决的不同。关于您的实际代码:这是基于运气。浏览器可能能够及时发送跟踪调用,也可能不会。如果跟踪代码以某种方式允许将事件附加到它,那将是最好的解决方案。否则,至少短暂的超时会增加跟踪调用实际通过的机会。
【解决方案2】:
<?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();  

【讨论】:

    【解决方案3】:

    想想你想在这里做什么:

    Google Analytics 代码由浏览器执行。 PHP 是在服务器上生成 HTTP 响应的预处理器

    所以,执行顺序是:

    1. 请求进来(在 Apache、NGINX 等上)
    2. PHP 获取请求并执行必要的操作
    3. PHP 生成的输出(通常是 HTML)被发送回客户端
    4. 客户端的浏览器呈现响应
    5. 响应中的任何 JavaScript 代码都在客户端的浏览器中运行

    PHP 将在第 2 步中生成 HTTP 重定向。它告诉客户端的浏览器转到其他地方并从第 1 步重新开始。但您基本上希望第 5 步在中间的某个地方执行。

    显然:这行不通。

    要么您找到一种从服务器端触发 Google Analytics(分析)的方法(这可能会破坏进行跟踪的目的),要么您只需要摆脱重定向(并用 JavaScript 位置更改替换它)或跳过跟踪调用。

    如果您只需要例如下载计数器,您可以让 PHP 在发出重定向之前记录命中。那会起作用的。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-03-16
      • 2015-11-01
      • 1970-01-01
      • 1970-01-01
      • 2019-05-22
      • 1970-01-01
      相关资源
      最近更新 更多