javascript - 使用 JavaScript/jQuery 通过 Google Analytics 跟踪重定向页面

标签 javascript jquery redirect google-analytics

我有一个重定向链接,www.example.com/redirect,它标识移动设备是 iOS 还是 Android,然后根据设备重定向到不同的链接。我尝试了在该论坛中找到的不同方法,但从未奏效。

下面是我尝试过的最新代码:

<script>

$(document).ready(function(){


function getMobileOperatingSystem() {
  var userAgent = navigator.userAgent || navigator.vendor || window.opera;

      // Windows Phone must come first because its UA also contains "Android"


    if (/android/i.test(userAgent)) {
        return "Android";
    }

    // iOS detection from: http://stackoverflow.com/a/9039885/177710
    if (/iPad|iPhone|iPod/.test(userAgent) && !window.MSStream) {
        return "iOS";
    }

}

    function DetectAndServe(){

if (getMobileOperatingSystem() == "Android") {
     ga('send', 'pageview', {
            'page': '/33red33',
            'hitCallback': function() {
              window.location.href = 'http://android.com';
           }
           });           

    }
if (getMobileOperatingSystem() == "iOS") {

      ga('send', 'pageview', {
            'page': '/33red33',
            'hitCallback': function() {
            window.location.href = 'http://apple.com';
           }
           }); 

    }

};

});

</script>

最佳答案

这可能只是这里的一个拼写错误,但您的代码中没有实际调用函数 DetectAndServe 的地方,将您的代码更改为下面的代码,它应该可以工作。

<script>

$(document).ready(function(){


function getMobileOperatingSystem() {
  var userAgent = navigator.userAgent || navigator.vendor || window.opera;

      // Windows Phone must come first because its UA also contains "Android"


    if (/android/i.test(userAgent)) {
        return "Android";
    }

    // iOS detection from: http://stackoverflow.com/a/9039885/177710
    if (/iPad|iPhone|iPod/.test(userAgent) && !window.MSStream) {
        return "iOS";
    }

}

    function DetectAndServe(){

if (getMobileOperatingSystem() == "Android") {
     ga('send', 'pageview', {
            'page': '/33red33',
            'hitCallback': function() {
              window.location.href = 'http://android.com';
           }
           });           

    }
if (getMobileOperatingSystem() == "iOS") {

      ga('send', 'pageview', {
            'page': '/33red33',
            'hitCallback': function() {
            window.location.href = 'http://apple.com';
           }
           }); 

    }

};
DetectAndServe();
});

</script>

关于javascript - 使用 JavaScript/jQuery 通过 Google Analytics 跟踪重定向页面,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46949241/

相关文章:

javascript - 处理页面中不同设备的脚本加载

apache - 如何在 .htaccess 503 重定向中保持网站 url 相同

c# - 使用 redmon 将打印机输出重定向到 C# 应用程序

javascript - 如何通过 unicode 属性获取 SVG 字体中的字形

javascript - Bootstrap 模式中的innerHTML

jQuery:按顺序将 <li> 标签插入列表中

apache - 为什么 Firefox 和 Chrome 坚持对手动输入的非 SSL 网站使用 HTTPS

javascript - 为什么像 Hotjar 和 Google Analytics 这样的网站使用复杂的跟踪代码而不是仅仅使用 &lt;script&gt; 标签?

javascript - 使用CSS定位元素

javascript - Jquery 克隆的 div 不像原来的那样运行?