如何在具有 file:/// URI 的 JavaScript Web 应用程序中使用 Google Analytics

How to use Google Analytics in a JavaScript Web Application that has file:/// URI

我正在开发仅前端 JavaScript 网络应用程序(使用的技术是 HTML5、CSS 和 JavaScript)。这个应用程序被注入到一个移动应用程序中,它采用我的 JS 网络应用程序并以一种奇特的方式显示它。

我想使用 Google Analytics 跟踪用户在我的应用程序中的活动,但问题是我注入移动应用程序的 JS 应用程序没有常规 URL 将 GA 用于网站/网络应用程序时需要,但它也不是移动应用程序 尝试将 GA 用于移动应用程序。结果是两者之间的混合移动和 Web 应用程序,我只能编辑我的 JS 应用程序。

我制作了下图以更好地形象化我的问题。

使用 jsconsole.com 我可以以编程方式访问我的应用程序并检查它的控制台,即使它已上传到 iPresent 中。没有错误。如果我提醒应用程序的 URL,我得到文件 URI:

alert( $( location ).attr( 'href ') );

//returns file:///var/mobile/..../index.html

我已经尝试了很多想要的解决方案(即 this or this),其中 none 有效。但我是这个领域的初学者,只是盲目地试图解决这个问题,所以可能错过了一些重要的注意事项。 Cookie 在我的 iPresent 应用程序中运行良好。

我最后使用的 GA 代码:

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

    if(window.localStorage) {
        ga('create', 'UA-NUMBER-1', 'none', {
          'storage': 'none'
          , 'clientId': window.localStorage.getItem('ga_clientId')
        });
        ga(function(tracker) {
          window.localStorage.setItem('ga_clientId', tracker.get('clientId'));
        });
    }
    else {
        ga('create', 'UA-NUMBER-1', 'none');
    }
    ga('send', 'pageview');
    </script>

是否可以让 GA 与这个没有常规 URL 但有文件 URI 的混合 Web 应用程序一起工作?如果是,怎么做?

谢谢你!

我建议你看看Analytics Measurement Protocol. It will allow you to track most, if not all, interactions that the Google Analtycis JavaScript does using HTTP requests to https://www.google-analytics.com/collect

这是一个纯 JavaScript 示例,说明如何使用 GET 发出请求:

var hit = 'https://www.google-analytics.com/collect?';
    hit += 'v=1';                 // Version.
    // Be sure to update the tid, Tracking ID, with your Google Analytics Tracking ID.
    hit += '&tid=UA-XXXXX-Y';     // Tracking ID / Property ID.
    hit += '&cid=555';            // Anonymous Client ID.
    hit += '&t=pageview';         // Pageview hit type.
    hit += '&dh=mydemo.com';      // Document hostname.
    hit += '&dp=/home';           // Page.
    hit += '&dt=homepage';        // Title.

httpGetRequest(hit);

function httpGetRequest(theUrl)
{
    var req = new XMLHttpRequest();
    req.open("GET", theUrl, true);
    req.send(null);
}

你应该看看 and Eloquent JavaScript Second Edition - Chapter 17 HTTP for more information about sending HTTP requests using JavaScript. If you have access to jQuery then you could also use jQuery.ajax()

提出请求后,您可以登录到您的 Google Analytics 帐户并在报告中查看综合浏览量。您可以在实时 >> 概览或行为 >> 站点内容 >> 所有页面中查看它。

在上图中,我转到行为 >> 网站内容 >> 所有页面,以红色显示。然后我将日期范围设置为 2015 年 10 月 21 日,以蓝色显示。突出显示的部分显示了我在 JavaScript hit 中设置的 Document hostnamePage多变的。请注意,我有一个过滤器可以更新页面以同时包含主机名,因此您可能只会看到页面的 /home

如果您有任何问题,请告诉我。