使用 Google Analytics 进行 Javascript 重定向

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/8692503/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-24 07:06:12  来源:igfitidea点击:

Javascript Redirect with Google Analytics

javascriptredirectgoogle-analyticssubdomainsubdirectory

提问by TryTryAgain

I need help figuring out how to successfully redirect while including Analytics code.

我需要帮助弄清楚如何在包含 Analytics 代码的同时成功重定向。

The code for that redirect file:

该重定向文件的代码:

<head>
<script type="text/javascript">
function delayedRedirect(){
    window.location = "https://market.android.com/developer?pub=Fractal%20Systems"
}
</script>
<script type="text/javascript">

  var _gaq = _gaq || [];
  _gaq.push(['_setAccount', 'UA-1234567-8']); <!--I have my real ID there-->
  _gaq.push(['_trackPageview']);

  (function() {
    var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true;
    ga.src = ('https:' == document.location.protocol ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js';
   var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s);
  })();

</script>
</head>
<body onLoad="setTimeout('delayedRedirect()', 3000)">
<h2>ADW.BuuF.Theme is no more! You will be redirected to new and better apps in 3 seconds.</h2>
</body>
</html>

This works as a redirect only if I don't include my Analytics code. I've tried moving the code around with no change.

仅当我不包含我的 Analytics 代码时,这才用作重定向。我试过在不做任何更改的情况下移动代码。

QUESTIONHow can I add a redirect, of any kind, and still be able to track with Google Analytics?

问题如何添加任何类型的重定向,并且仍然能够使用 Google Analytics 进行跟踪?

I've tried PHP redirects with no success and am pretty sure htaccess redirects wont help although I'm open to suggestions.

我尝试过 PHP 重定向但没有成功,我很确定 htaccess 重定向不会有帮助,尽管我愿意接受建议。

The reason I'm using a JavaScript redirect is so I can continue to track with Google Analytics and also show a little message or make a custom page with the delay.

我使用 JavaScript 重定向的原因是我可以继续使用 Google Analytics 进行跟踪,并显示一条小消息或制作带有延迟的自定义页面。

Thanks for any help. Doesn't have to be JS, please, any input is welcome if you know of a solution.

谢谢你的帮助。不必是 JS,如果您知道解决方案,欢迎任何输入。

采纳答案by TryTryAgain

Using meta refreshworked like a charm! Legacy FTW! Thanks, @Balexandre

使用元刷新就像一个魅力!传统FTW!谢谢,@Balexandre

<html>
<head>
<meta http-equiv="refresh" content="5; url=https://market.android.com/developer?pub=Fractal%20Systems">
<script type="text/javascript">

  var _gaq = _gaq || [];
  _gaq.push(['_setAccount', 'UA-1234567-8']);
  _gaq.push(['_trackPageview']);

  (function() {
    var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true;
    ga.src = ('https:' == document.location.protocol ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js';
    var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s);
  })();

</script>
</head>
<body>
<h2>ADW.BuuF.Theme is no more! You will be redirected to new and better apps in 5 seconds.</h2>
</body>
</html>

RECAP: I am now able to redirect while tracking those redirects using Google Analytics!

回顾:我现在可以在使用 Google Analytics 跟踪这些重定向的同时进行重定向!

Meta Refresh (Taken from wikipedia)

元刷新(取自维基百科

Examples

例子

Place inside to refresh page after 5 seconds:

放置在里面 5 秒后刷新页面:

<meta http-equiv="refresh" content="5">

Redirect to http://example.com/after 5 seconds:

5 秒后重定向到http://example.com/

<meta http-equiv="refresh" content="5; url=http://example.com/">

Redirect to http://example.com/immediately:

立即重定向到http://example.com/

<meta http-equiv="refresh" content="0; url=http://example.com/">

回答by mike

Note: _gaq.pushallows pushing of functions onto the queue. The following code should redirect after 250 milliseconds (to allow time for the tracking pixel) after the _trackPageview:

注意:_gaq.push允许将函数推入队列。以下代码应在 _trackPageview 之后 250 毫秒后重定向(为跟踪像素留出时间):

var _gaq = _gaq || [];
_gaq.push(['_setAccount', 'UA-1234567-8']);
_gaq.push(['_trackPageview']);
_gaq.push(function() {
    setTimeout(function() {
        window.location = "https://market.android.com/developer?pub=Fractal%20Systems";
    }, 250);
});

(function() {
    var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true;
    ga.src = ('https:' == document.location.protocol ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js';
    var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s);
})();

回答by Jarrod

If you're using the new GA code you can simply replace this line ga('send', 'pageview');with this code:

如果您使用的是新的 GA 代码,您只需将此行替换ga('send', 'pageview');为以下代码:

ga('send', 'pageview', {
  'hitCallback': function() {
      window.location = "http://www.your-site.com";
  }
});

Example in full:

完整示例:

  (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-xxxxxxx-2', 'auto');

ga('send', 'pageview', {
  'hitCallback': function() {
      window.location = "http://www.your-site.com";
  }
});

回答by jfriend00

I'd suggest changing your Google Analytics code to be synchronous instead of asychronous by changing it to this:

我建议将您的 Google Analytics 代码更改为同步而不是异步,方法是将其更改为:

<script type="text/javascript">
  var _gaq = _gaq || [];
  _gaq.push(['_setAccount', 'UA-1234567-8']);
  _gaq.push(['_trackPageview']);
</script>
<script type="text/javascript" src="http://www.google-analytics.com/ga.js"></script>

This should guarantee that it runs before your redirect code kicks in and it should be out of the way of your redirect script so there is no interference. As you have it now, you're playing a guessing game for how long the GA script will take to load and that it will load and do it's job in under 3 seconds. That may usually be the case, but there is no reason to load it asynchronously like you are and have to play that game. Load it synchronously and it will do it's job before your javascript redirect fires.

这应该保证它在您的重定向代码启动之前运行,并且它应该不受您的重定向脚本的影响,因此没有干扰。正如您现在所拥有的那样,您正在玩​​一个猜谜游戏,猜测 GA 脚本需要多长时间才能加载,并且它将在 3 秒内加载并完成工作。通常可能是这种情况,但没有理由像您一样异步加载它并且必须玩那个游戏。同步加载它,它会在您的 javascript 重定向触发之前完成它的工作。

It might even be possible to just put the redirect directly after the GA code like this and minimize the time that your placeholder page is displayed:

甚至可以像这样将重定向直接放在 GA 代码之后,并最大限度地减少占位符页面的显示时间:

<script type="text/javascript">
  var _gaq = _gaq || [];
  _gaq.push(['_setAccount', 'UA-1234567-8']);
  _gaq.push(['_trackPageview']);
</script>
<script type="text/javascript" src="http://www.google-analytics.com/ga.js"></script>
<script type="text/javascript">
  window.location = "https://market.android.com/developer?pub=Fractal%20Systems";
</script>

回答by Ghans

The code providedby Mikeworks indeed. However, I found that removing the timer entirely works as well. The __utm.gif request is then aborted, but all information has been sent. The window just redirects and doesn't wait for the reply (which is simply a 200 status). I tested this and it seems to be working nicely.

提供的代码麦克工作确实。但是,我发现删除计时器也完全有效。__utm.gif 请求随后被中止,但所有信息都已发送。窗口只是重定向而不等待回复(这只是一个 200 状态)。我对此进行了测试,它似乎运行良好。

var _gaq = _gaq || [];
_gaq.push(['_setAccount', 'UA-1234567-8']);
_gaq.push(['_trackPageview']);
_gaq.push(function() {
  window.location = "https://market.android.com/developer?pub=Fractal%20Systems";
});


(function() {
    var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true;
    ga.src = ('https:' == document.location.protocol ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js';
    var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s);
})();

回答by CfSimplicity

Meta refresh is generally discouraged because of usability concerns (especially with a short, or no delay), but as a fallbackfor clients with no javascript I think it's perfectly valid in this case.

由于可用性问题(尤其是短暂或没有延迟),通常不鼓励元刷新,但作为没有 javascript 的客户的后备,我认为在这种情况下它是完全有效的。

If you combinethe synchronous ga.js call with a meta refresh you get the best of both worlds: an almost instant, tracked redirect if JS is enabled; a delayed but still effective redirect if not (and a hard link in the body just in case all else fails).

如果您同步 ga.js 调用与元刷新结合起来,您获得两全其美的效果:如果启用了 JS,则几乎是即时的、可跟踪的重定向;如果没有,则延迟但仍然有效的重定向(以及正文中的硬链接,以防万一)。

<html>
<head>
    <!--For JS disabled: decent delay, both for usability and to allow plenty of time for JS to work if enabled -->
    <meta http-equiv="refresh" content="5;https://market.android.com/developer?pub=Fractal%20Systems"/>
    <script>
        var _gaq = _gaq || [];
        _gaq.push(['_setAccount', 'UA-1234567-8']);
        _gaq.push(['_trackPageview']);
    </script>
    <!--Synchronous call to ensure tracking fires before JS redirect-->
    <script type="text/javascript" src="//www.google-analytics.com/ga.js"></script>
    <script>
        /* if JS is enabled this will normally fire well before the meta refresh delay ends: an almost instantaneous redirect */
        window.location="https://market.android.com/developer?pub=Fractal%20Systems";
    </script>
</head>
<body>
    <!-- Include a hard link in case both js and the meta refresh fail -->
    <p>Redirecting you to <a href="https://market.android.com/developer?pub=Fractal%20Systems">https://market.android.com/developer?pub=Fractal%20Systems</a></p>
</body></html>

回答by jamescridland

There's a good answer here: https://www.domsammut.com/code/setting-up-hitcallback-using-google-universal-analytics

这里有一个很好的答案:https: //www.domsammut.com/code/setting-up-hitcallback-using-google-universal-analytics

In short, you'd do it using an event, and you use the hitCallback function.

简而言之,您可以使用事件来完成它,然后使用 hitCallback 函数。

回答by Karthik Sankar

This approach does not require a delay. First execute google analytics code synchronously and then redirect.

这种方法不需要延迟。首先同步执行google分析代码,然后重定向。

<html>
<head>
<script src="//www.google-analytics.com/analytics.js"></script>
  <script>
    var tracker = ga.create('UA-xxxxxxxx-x', 'auto');
    tracker.send('pageview');
    window.location='http://your-url.com';
  </script>
</head>
<body>
</body>
</html>

回答by John Peterson

I think maybe just use jquery ready method so it won't start the timer till the page is fully loaded...

我想也许只是使用 jquery ready 方法,所以它不会在页面完全加载之前启动计时器......

<script type="text/javascript" charset="utf-8">
$(document).ready(function() {       
    setTimeout(function() {
        //alert("redirecting!");
        window.location = '<?= $url ?>';
    }, 3000);
});
</script>