How to use Google Analytics with Phonegap without a plugin?

后端 未结 14 1949
北海茫月
北海茫月 2020-11-28 03:03

I am making an app and I want to get analytics from the users. I tried to use the Phonegap Plugin, but I didn\'t have any luck trying to implement it.

I was wonderin

相关标签:
14条回答
  • 2020-11-28 03:39

    This is February 2017 and there is no need to edit analytics.js, nor for a library or plugin anymore, or at least I had no need for them. Many things that were said in the past years are deprecated or just obsolete, so here is my up-to-date comprehensive guide.

    1. The config.xml file

    In your config.xml, you must allow the cross-site request:

    <access origin="https://www.google-analytics.com" />

    2. The HTML

    In your CSP meta tag, if you choose to have one, you must also allow calls to Google. It may look like:

    <meta http-equiv="Content-Security-Policy" content="default-src 'self' data: gap: 'unsafe-inline' 'unsafe-eval' https://ssl.gstatic.com https://www.google-analytics.com;">

    3. The javascript

    Here is the commented code for a webapp that can run both in the browser and in a Cordova packaged app. You can ignore the else block if you don't care about the browser.

    // the default GA code, nothing to change
    (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','https://www.google-analytics.com/analytics.js','ga');
    
    var fields = {
      // note: you can use a single tracking id for both the app and the website,
      // don't worry it won't mix the data. More about this in the 3rd section
      trackingId: 'UA-XXXXXXXX-Y'
    };
    
    // if we are in the app (the protocol will be file://)
    if(document.URL.indexOf('http://') !== 0){
    
      // we store and provide the clientId ourselves in localstorage since there are no
      // cookies in Cordova
      fields.clientId = localStorage.getItem('ga:clientId');
      // disable GA's cookie storage functions
      fields.storage = 'none';
    
      ga('create', fields);
    
      // prevent tasks that would abort tracking
      ga('set', {
        // don't abort if the protocol is not http(s)
        checkProtocolTask: null,
        // don't expect cookies to be enabled
        checkStorageTask: null
      });
    
      // a callback function to get the clientId and store it ourselves
      ga(function(tracker){
        localStorage.setItem('ga:clientId', tracker.get('clientId'));
      });
    
      // send a screenview event
      ga('send', {
        // these are the three required properties, check GA's doc for the optional ones
        hitType: 'screenview',
        // you can edit these two values as you wish
        screenName: '/index.html',
        appName: 'YourAppName'
      });
    }
    // if we are in a browser
    else {
    
      ga('create', fields);
    
      // send a pageview event
      ga('send', {
        // this is required, there are optional properties too if you want them
        hitType: 'pageview'
      });
    }
    

    3. Your GA account

    • To monitor the traffic of the mobile app, create a view of the App type.

    If you don't need to monitor the traffic of your web app from a website, you can stop reading here, otherwise read on. I assume you are using a single account for the tracking of both the website and the app.

    • Apply the custom filter named "Application? => yes" on the created view so that it will only show the screenview hits. There is an official guide here
    • Then, to track the traffic from the website, create a second view of the Website type. Apply a custom filter "Application? => no" on it.
    • If you want a merged view of your traffic online and in-app, create a third view of the App type. By default (without filter), it will show all data.

    Additional notes

    • Everything goes over https now, no need for the http protocol anymore in your <access> and CSP
    • Be aware that writing *.google-analytics.com in the CSP would not work. Although that policy works in Chrome (56), it doesn't in Cordova (5.6.0)
    • Google analytics does not require any application permissions like ACCESS_NETWORK_STATE or ACCESS_WIFI_STATE like I've read elsewhere
    • All of this was tested with an Android app (I expect it to work in iOS apps as well), with the Crosswalk plugin installed
    0 讨论(0)
  • 2020-11-28 03:40

    The year is 2019 the month November, Google keeps updating their APIs, "best" pratices and etc. without ANY good documentation or backward compatibility.

    Here is what I did for my solution I used combination from two of the answers here.

    Before I start IF you are reading this and you are having problem with cordova's google analytics/ firebase plugins JUST LEAVE THEM, when using webview you don't need any of the plugins.

    1) First you have to go to the Google Analytics and create a new "Property" that will measure "Website" activity (who knows by the time you are reading this how those will be called but everything should be in the "Admin" part of the panel).

    One of the questions that comes to mind here is "But it wants url, I don't have url I am making Cordova App"

    And yes you are right, for the URL I used my app's API (Which means most likely any url you enter there will work)

    2) Then Follow the instructions in the answer of @Louis Ameline which is this one With that you will have the script loaded in your app and ready for usage.

    3) By this time now if you run your app in browser everything should be fine and you probably will be able to see in the "Live analytics" that there is 1 online user.

    4) Now for this to work in Webview you should follow the answer of @Guillaume Gendre (the updated one) here. I just copy pasted the code (of course with my trackingId) and now when I build the application and run it on my Android it works as expected and the analytics are sent.


    I hope my solution actually helps someone and saves some time. Just leave all plugins because they lead to a deep hole of unsuccessful builds that just does not end because of version problems.

    Also my App is React based but that should not matter at all, it should work with all frameworks and libraries because this is pure js. I suggest you use that kind of solution for this type of problems because it is not connected to any specific libraries.

    0 讨论(0)
提交回复
热议问题