How to use Google Analytics with Phonegap without a plugin?

后端 未结 14 2056
北海茫月
北海茫月 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:36

    For me it turned out that no plugin is needed! I have Angular 8 app wrapped in Cordova (so similar use case as with Ionic) I registered new web site in Google Analytics. I modified code form GA to look like this:

    const gaScript = document.createElement('script');
            gaScript.src = "https://www.google-analytics.com/analytics.js";
            gaScript.type = "text/javascript";
            document.getElementsByTagName('head')[0].appendChild(gaScript);
            gaScript.onload = (ev: Event) => {
                const GA_LOCAL_STORAGE_KEY = 'ga:clientId';
                window['ga']('create', 'XXXX-XXXXX', {
                    'storage': 'none',
                    'clientId': localStorage.getItem(GA_LOCAL_STORAGE_KEY)
                });
                window['ga'](function(tracker) {
                    localStorage.setItem(GA_LOCAL_STORAGE_KEY, tracker.get('clientId'));
                });
    
                // THIS IS FOR FILE URL SUPPORT
                window['ga']('set', 'checkProtocolTask', function(){ /* noop */});
                console.log('GA OK!')
            }
    

    And then I can use GA in regular way: window['ga']('send', 'pageview', screenName); This is because there is no automatic tracking of page changes while serving using file:// protocol.

    This solution is very handy as it is DRY, because I have just one way to embed Google Analytics in my app for both hybrid and hosted versions.

提交回复
热议问题