Adding Google Analytics to Adobe Air HTML/Javascript App - javascript

I am attempting to add google analytics tracking to an Adobe Air app created with HTML and javascript.
I have tried adding the ga.js file and using it like I would in a webpage:
<script type="text/javascript" src="lib/js/ga.js"></script>
<script type="text/javascript">
var pageTracker = _gat._getTracker("UA-********-1");
pageTracker._initData();
pageTracker._trackPageview('/test');
</script>
But this doesn't seem to register anything on the analytics dashboard.
Have also tried using the GA for flash actionscript library but I can't seem to create an instance of the GATracker as it needs a DisplayObject?
EDIT
using the information from grapefrukt I tried the following:
air.Sprite = window.runtime.flash.display.Sprite;
air.GATracker = window.runtime.com.google.analytics.GATracker;
var tracker = new air.GATracker( new air.Sprite(), "UA-XXXXXXX-X", "AS3", false );
but I get the following error:
TypeError: Error #1009: Cannot access a property or method of a null object reference

NOTE: I originally misread your question to be about how to use gaforflash, but I'll post this anyway since I've already typed it up and it might be of some use.
You can the constructor whatever DisplayObject you like, normally you'd use your document class, but anything will work. As far as I can understand it's only really used for displaying debug info.
var tracker:AnalyticsTracker = new GATracker( new Sprite, "UA-XXXXXXX-X", TrackerMode.AS3, false );
Setting the TrackerMode to AS3 let's the flash communicate directly with the tracking servers, so you don't need the javascript from google's servers.
I can't help you with the communication between js/as3, but that should be fairly easy.

Probably not useful to the OP, but just spent the whole day working around this so hopefully my solution will save someone else that time.
So the reason the ga.js code can't be used directly from an AIR app written in javascript is that AIR won't set the cookie for pages that are stored within the application itself. To work around this, I downloaded ga.js to the application and modified it so that it doesn't rely on the document.cookie function.
In the application, I have:
<script type="text/javascript">
var cookies = {};
document.__defineSetter__('_cookie', function(c) {
var epos = c.indexOf('=');
var spos = c.indexOf(';', Math.max(0, epos));
if (epos == -1 || spos == -1) { return; }
var name = c.substring(0, epos);
var value = c.substring(epos + 1, spos);
cookies[name] = value;
});
document.__defineGetter__('_cookie', function() {
var a = [];
for (var name in cookies) {
a.push(name + '=' + cookies[name]);
}
return a.join('; ');
});
var _gaq = _gaq || [];
_gaq.push(['_setAccount', 'UA-XXXXXX-1']);
_gaq.push(['_trackPageview', path])
(function() {
var ga = document.createElement('script');
ga.type = 'text/javascript';
ga.async = true;
// custom GA code which uses document._cookie instead of
// document.cookie
ga.src = 'js/ga.js';
var s = document.getElementsByTagName('script')[0];
s.parentNode.insertBefore(ga, s);
})();
</script>
Ideally, we'd be able to override the cookie method, but unfortunately, it doesn't seem possible in webkit as implemented for AIR. So in ga.js, I replaced all instances of J.cookie with J._cookie. Once that's done, ga.js should believe that it's writing cookies and function normally.
In the interest of full disclosure, I actually access the above analytics code through an iframe, but since ga.js is being served locally, I suspect it's no longer necessary and didn't want to complicate the solution by adding the bridge logic.

Related

Integrating multiple tawk.to widgets on one page

I have been trying to integrate multiple tawk.to widgets inside popups,
<div id="tawk_xxx"><br></div>
<script type="text/javascript">
var Tawk_API = Tawk_API || {},
Tawk_LoadStart = new Date();
Tawk_API.embedded = 'tawk_5f96cfd1aca01a168835cf5a';
(function() {
var s1 = document.createElement("script"),
s0 = document.getElementsByTagName("script")[0];
s1.async = true;
s1.src = 'https://embed.tawk.to/xxxx/xxx';
s1.charset = 'UTF-8';
s1.setAttribute('crossorigin', '*');
s0.parentNode.insertBefore(s1, s0);
})();
</script>
the problem is when the JS snippet loads, it sets some global variable in the window object that should be cleared to run the Tawk_API again whereas I want to keep both instances running at the same time. I tried using Iframes, the problem with iframes is that the browsers will consider as third party cookies, and the iframe will be blocked if the browser does not allow them
so is there any way around this issue

Cookiebot Cookie Consent Script

I am adding ZohosalesIQ to the CookieBot Prior Consent widget on w WP install.
This script given by zoho is
<script type="text/javascript" data-cookieconsent="statistics">
var $zoho = [];
var $zoho = $zoho || {};
$zoho.salesiq = $zoho.salesiq || {
widgetcode: "1c636a8a8d8e3410b7e579760898b7768f3cb213adb21970788a3891735df801800b6e4a1385c37b0f792b9ee54ce",
values: {},
ready: function() {}
};
var d = document;
s = d.createElement("script");
s.type = "text/javascript";
s.id = "zsiqscript";
s.defer = true;
s.src = "https://salesiq.zoho.eu/widget";
t = d.getElementsByTagName("script")[0];
t.parentNode.insertBefore(s, t);
d.write("<div id='zsiqwidget'></div>");
</script>
I am supposed to be adding <script type="text/plain" data-cookieconsent="statistics">
to the script tag to enable prior consent on cookies created by this script however, when I add this it breaks and fails to load.
Console is empty but the page renders as a white page after pre-load. When I add the code with the jaavscript type tag, it works fine.
I've tried popping itto a call back function but no joy :(
Any pointers would be great.
If the script tag is using the deprecated JavaScript function “document.write” it might cause the problem you have described above because using this function the script is loaded synchronously and it will then clear the window content (generates blank page).
To prevent this issue please make sure that the script is loaded asynchronously since the Cookiebot triggers all scripts asynchronously (i.e. to wait for the visitor’s consent) in order to work properly.
You need rewrite it to use a different approach e.g. “document.write = function(node) {document.body.insertAdjacentHTML(‘beforeend’, node);}”

Setting up Google Analytics (gtag) to track ad blocking

I've followed an online article as closely as possible (along with reading up in other articles) to track ad blocking but Google seems to have changed their GA tag lately to a new version called GTAG (no longer the same old "universal" tag.
https://www.kaushik.net/avinash/adblock-tracking-google-analytics-code-metrics-reports
I haven't found enough online documentation on how to set this up properly along with setting up the segment in GA to track adblock: true or false. So far, I just get a chart that tracks the adblocking event.
I am a GA GTM newbie and I've always found their UI horrible to navigate but that's besides the point. I hope someone can help with some tips if I've set up incorrectly. Thanks!
Here's what I have in GTM as a new tag as I didn't think I could use the standard GA tag where you just enter your id (I'd have to put the extra code I needed somewhere else and it would get messy imo):
<!-- Global site tag (gtag.js) - Google Analytics -->
<script async src="https://www.googletagmanager.com/gtag/js?id=UA-ID">
</script>
<script>
var isAdBlockEnabled;
(function AdBlockEnabled() {
var ad = document.createElement('ins');
ad.className = 'AdSense';
ad.style.display = 'block';
ad.style.position = 'absolute';
ad.style.top = '-1px';
ad.style.height = '1px';
document.body.appendChild(ad);
isAdBlockEnabled = !ad.clientHeight;
document.body.removeChild(ad);
return isAdBlockEnabled;
})()
window.dataLayer = window.dataLayer || [];
function gtag(){dataLayer.push(arguments);}
gtag('js', new Date());
// Configures custom dimension<Index> to use the custom parameter
// 'dimension_name' for 'GA_TRACKING_ID', where <Index> is a number
// representing the index of the custom dimension.
gtag('config', 'UA-ID', {
'custom_map': {'1': 'AdsBlocked'}
});
// Sends the custom dimension to Google Analytics.
gtag('event', 'adsBlocked', {'AdsBlocked': isAdBlockEnabled});
</script>
Also, here's my GA segment setup - let me know if you guys need to see anything more:
I'm not sure when Google changed their tag but the old one seemed a lot more straightforward to set up. Thanks for the advice !

Google analytics javascript snippet analysis

Just wondering how google analytics code snippet works in terms of javascript programming.
<script type="text/javascript">
var _gaq = _gaq || [];
_gaq.push(['_setAccount', 'UA-XXXXX-X']);
_gaq.push(['_trackPageview']);
(function() {
var ga = document.createElement('script');
ga.src = ('https:' == document.location.protocol ? 'https://ssl' :
'http://www') + '.google-analytics.com/ga.js';
ga.setAttribute('async', 'true');
document.documentElement.firstChild.appendChild(ga);
})();
</script>
1) We push 2 elements onto _gaq array but when does it actually get executed/used especially since ga.js is sitting on remote server? I tried looking into ga.js code but it's really confusing.
2) What would happen if the site was https:// but we still linked the javascript as http://www.google-analytics.com/ga.js
(function() {
var ga = document.createElement('script');
ga.src = 'http://www.google-analytics.com/ga.js';
ga.setAttribute('async', 'true');
document.documentElement.firstChild.appendChild(ga);
})();
_gaq is a global variable (in browsers global variables are stored in Window object)
And its referenced in https://ssl.google-analytics.com/ga.js like this:
var He = function () {
var a = W._gaq,
b = l;
if (a && Aa(a[p]) && (b = "[object Array]" == Object[y][w].call(Object(a)), !b)) {
Z = a;
return
}
W._gaq = Z;
b && Z[p][xa](Z, a)
};
Also W refers to Window global variable (the script is minified to save bytes):
var W = window,
For your convenience, I have pasted a formatted version of ga.js here:
http://pastebin.com/sBmeSg9M
Look at line 603 and line 1956.
The Google Analytics code gets loaded and run on your page, at your domain, hence it has access to window and all the variables defined on it. _gaq is the magic variable name that Google's code inspects when it runs to see what has been defined and uses the values it finds to begin tracking things. It then tracks changes to this variable for the duration your page is loaded (which is how it does click event tracking etc).
As others have mentioned, failing to use the HTTPS URL for Google Analytics on a page served over HTTPS will lead to a warning about "insecure content". Stick with the code Google provides, they do so for a reason.
2) What would happen if the site was https:// but we still linked the javascript as http://www.google-analytics.com/ga.js
This would prevent nearly all modern browsers (e.g. Chrome) to load the JS file and show a little warning to the user that there is "Insecure content".
The reason behind this is, that loading the JS file would allow MITM attacks without a SSL certificate warning.
2.: Then your SSL-certificate doesn't work correctly. There is non-ssl (https) script included to your SSL-site. Is that what you mean?

Google Analytics: How to track hits to mobile site as hits to main site

We are developing a completely new mobile version of our site, it is a HTML5 site written using Sencha Touch 2 (Ext JS, JavaScript).
We are using Google Analytics on our main site, and we would like to use GA on the mobile site as well. However our desired use case is a little special:
We would like hits to articles on the mobile site to be tracked as hits to the corresponding article on the main site.
The reasoning behind this is the desire to aggregate the statistics, and not have the data tracked separately.
The domains and URL structure is different for the two sites, although the site hierarchy is somewhat similar (they both get content from a Sharepoint backend), and herein lies the challenge. We cannot only change the domain using something like 'setDomainName'.
On every page in the mobile version, we have available the full URL to the original page/article on the main site. What we would like to do is tell Google to track the view as a hit to that URL instead of the one we are actually on.
I've seen some threads (f ex here) regarding 'trackPageView' and it may be sufficient for our needs, however I am not entirely sure. It sounds a little too simple, but it may also be that I am not seeing the obvious solution here.
Could we provide this method with the desired hit URL and that's it? Would it work then to have a script in the header that checks for a set variable with this URL, and if it exists call 'trackPageView' with it as a parameter, if not just track a regular hit?
Any help with syntax for this approach is welcome.
All help & suggestions appreciated here!
I've scoured GA docs without much helping information on this special case.
Yes it is that simple use the track page view event and pass the corresponding URL parameters. In sencha all your views are going to exist in the same HTML page so you need to call this programmatically.
Include the same tracking code as you use in your live site with the same ID... This should work as you expect...
Very good question...Hope it helps...
Here's GA Tracking spelled out and made simple for ST2+. I've included how to initialise, set up basic navigation tracking, and several alternatives including custom variable & event tracking.
/*
Standard method to init GA tracking.
These can be fired from launch.
*/
initialiseGoogleAnalytics : function() {
//Add Google Analytics Key
window._gaq = window._gaq || [];
window._gaq.push(['_setAccount', MyApp.config.googleAnalytics.code]);
window._gaq.push(['_setDomainName', MyApp.config.googleAnalytics.domain]);
window._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);
})();
},
/*
This method can be set to a globally accessable reference.
For instance:
MyApp.Util = {}; // reference for common utility functions
MyApp.Util.gaTrackEvent = function(data) {};
Thus allowing MyApp.Util.gaTrackEvent(data) from anywhere in app.
Alternatively, add as function to Application for
this.getApplication().gaTrackEvent(data);
*/
gaTrackEvent : function(data) {
//Push data to Google Analytics
// optional prefix for mobile devices - unnecessary for your interest
var prefix = 'mobile/';
// don't track homepage/default hits
if (data == 'home') {
//Ignore Home
return;
}
// basic tracking
_gaq.push(['_trackPageview', prefix + data]);
// OPTIONAL ALTERNATIVES FOR DETAILED TRACKING
// detailed tracking - condensed
_gaq.push(['_setCustomVar',
1, // custom variable slot
'customEventName', // custom variable name
'value1|value2|value3', // multiple values using 1 slot
2 // sets scope to session-level
]);
_gaq.push(['_trackEvent',
'ParentEventName',
'SomeValue'
]);
// detailed tracking - each variable using own slot
_gaq.push(['_setCustomVar',
1,
'stage1',
'value1',
2
]);
_gaq.push(['_setCustomVar',
2,
'stage2',
'value2',
2
]);
_gaq.push(['_setCustomVar',
3,
'stage3',
'value3',
2
]);
_gaq.push(['_trackEvent',
'ParentEventName',
'SomeValue'
]);
}
/*
Set up a controller to handle GA tracking.
This way you can keep the unique events you wish to track central,
while also handling default tracking and SEO.
For example, a controller for Registration might want tracking on success.
this.getRegistration().fireEvent('registrationsuccess');
*/
config: {
control: {
"navigationview": {
activeitemchange: 'generalSEOhandler'
},
"#registration": {
registrationsuccess: 'onRegistrationSuccess'
},
...
},
},
generalSEOhandler: function(container, value, oldValue, eOpts) {
if (value === 0) {
return false;
}
// ignoreDefaultSeo - boolean custom config that can be applied to views.
var ignoreDefaultSeo = value.getInitialConfig('ignoreDefaultSeo');
if (Ext.isDefined(ignoreDefaultSeo) && ignoreDefaultSeo == 1) {
// optional handler for special cases...
} else {
// Use default
var itemId = value.getItemId();
itemId = itemId.replace(/^ext-/,''); // Remove the prefix ext-
itemId = itemId.replace(/-[0-9]?$/,''); // Remove the suffix -1,-2...
// Alternatively use xtype of the view (my preference)
// This will require the xtypes of your views to match the main site pages.
var itemId = value.config.xtype;
this.trackEvent(itemId);
//console.log('USE DEFAULT', value.getId(), value.getItemId(), value);
}
},
onRegistrationSuccess: function(eventOptions) {
var app = this.getApplication(),
trackUrl;
trackUrl = 'new-member';
if (Ext.isDefined(app.accountReactivated) && app.accountReactivated == 1) {
trackUrl = 'reactivated-member';
}
if (Ext.isDefined(app.registeredUsingFacebook) && app.registeredUsingFacebook == 1) {
trackUrl += '/facebook';
} else {
trackUrl += '/non-facebook';
}
// console.log('onRegistrationSuccess', trackUrl);
this.trackEvent(trackUrl);
},
trackEvent: function(data) {
// if using MyApp.Util.gaTrackEvent() technique
MyApp.Util.gaTrackEvent(data);
// if gaTrackEvent() an application method
this.getApplication().gaTrackEvent(data);
}
}
I found this article talking about Google Analytics and Sencha Touch
http://wtcindia.wordpress.com/2013/03/21/using-google-analytics-in-sencha-touch-based-mobile-website/

Categories

Resources