Windows 8 Javascript Integration Guide
Notes and Updating from Previous Versions
If you are updating from prior to version 2.4 note there are now changes to the implementation, notably the removal of localyticsSession.init()- this step is now part of assigning the localyticsSessiion variable.
Ten Minute Instrumentation Instructions
- 1) Log into your Localytics account or create an account if you do not already have one.
- 2) In your account, create a new application and copy the application key.
- 3) Download the HTML5 Client Library. It is distributed unminified for readability.
- 4) Add it to the js folder in your project
- 5) Include it, after default.js by adding the following to your default.html:
<script src="/js/localytics.js"></script>
- 6) Start the section when the app is launched by adding the following to app.onactivated:
var localyticsSession = LocalyticsSession("APP KEY FROM STEP 2", options); localyticsSession.open(); localyticsSession.upload();Note the polling option. By default the html5 library polls the app to see if the user is still using it but on Windows 8 there is are robust viewchange events so this is not necessary. - 7) Close the session when the app leaves the foreground and open a new one when it returns. By default, if the user is gone for less than 15 seconds the previous session is resumed. This is done by catching the changeview notification:
var onVisibilityChange = function (args) { var state = document["visibilityState"]; if (state == "visible") { localyticsSession.open(); localyticsSession.upload(); } else if (state == "hidden") { localyticsSession.close(); localyticsSession.upload(); } }; document.addEventListener("visibilitychange", onVisibilityChange, false);
Events (Recommended)
Unsure what events to tag? Check our Event Recommendations
Anywhere in your application where an interesting event occurs you may tag it by adding the following line of code:
… existing JavaScript action...
localyticsSession.tagEvent("Event Name");
where “Interesting Event” is a string describing the event. It is recommended that you read the Tagging section in the Developer’s Integration Guide in order to get the most value out of your tags.
For some events, it may be interesting to collect additional data about the event. Such as how many lives the player has, or what the last action the user took was before clicking on an advertisement. This is accomplished with the second form of tagEvent, which takes a hash of attribute name / value pairs:
localyticsSession.tagEvent("Event Name", {"AttributeName": attributevalue, "AttributeName2": attributevalue2});
For example, recording an article view in a news application might look like this:
localyticsSession.tagEvent("Article View", {"Page Name":"Baseball-Headlines" , "Section":"sports"});
It is recommended that you read the Event Attributes section in the Developer’s Integration Guide in order to get the most value out of your attributes.
Important Note:
Make sure never to upload data from a continuous set or from user-generated values. Consider tagging a file transfer event with the file size and name. If the file can be any size this will cause many buckets to be created on our server. When you look at the data in the charts, there will be many charts each with only a few results and the data will be in-actionable. Instead, it is necessary to bucket this data into groups such as “0 to 1K”, “1K to 50K”, etc. Similarly, if you allow users to create their own name for the file, you will have a list of thousands of unique file names that are also not useful to view in the dashboard. See our blog post for an example.
Screen Flows (Premium)
When an activity is shown, it can be tagged so that all user flows through the application can be tracked.To do this, add a tagScreen call in the onCreate call after the session open for each of your views.
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
// Activity Creation Code
// Instantiate the object
this.localyticsSession = new LocalyticsSession(
this.getApplicationContext(), // Context used to access device resources
"A Unique Key"); // Key generated on the webservice
this.localyticsSession.open(); // open the session
this.localyticsSession.tagScreen("Splash");
this.localyticsSession.upload(); // upload any data
// At this point, Localytics Initialization is done. After uploads complete nothing
// more will happen due to Localytics until the next time you call it.
}
Screen Flows
Whenever a page is loaded it can be tagged using the tagScreen API. This should be called after the open for each page. Names should be statically defined to avoid recording too many values which will make the charts hard to get value out of.
For example, this is the screen tag for the Article View:
this.localyticsSession.tagScreen("Article View");
Options
The following options may be passed to the assignment of the localyticsSession variable:
- appVersion
- networkCarrier
- polling
- uploadTimeout
- sessionTimeoutSeconds
- storage
- logger
- appVersion: string; your application’s version (default: undefined)
- networkCarrier: string; the curent device’s carrier (default: undefined)
- polling: number; frequency in milliseconds that Localytics polls for the end of a session (default: 10,000)
- uploadTimeout: number; upload timeout in milliseconds (default: 60,000)
- sessionTimeoutSeconds: number; timeout in seconds until Localytics marks the session as closed (default: 30)
- storage: number; maximum number of characters Localytics is allowed to use from the localStorage (default: 100,000)
- logger: boolean; whether to enable console logging (default: false)
Example with parameters
var options = {
appVersion: "v1.5",
networkCarrier: "AT&T"
polling: 10000,
uploadTimeout: 60000,
sessionTimeoutSeconds: 30,
storage: 100000,
logger: true};
var localyticsSession = LocalyticsSession("APP_KEY_FROM_STEP_2", options);
});
Sample
You can download a working sample project here. The two key files, are also provided here: default.js
// For an introduction to the Blank template, see the following documentation:
// http://go.microsoft.com/fwlink/?LinkId=232509
(function () {
"use strict";
var app = WinJS.Application;
var activation = Windows.ApplicationModel.Activation;
WinJS.strictProcessing();
// open and close the session on visibility change events. This causes the session to be resumed if the
// user is gone for less than 15 seconds, otherwise a new session is created.
var onVisibilityChange = function (args) {
var state = document["visibilityState"];
if (state == "visible")
{
localyticsSession.open();
localyticsSession.upload();
}
else if (state == "hidden") {
localyticsSession.close();
localyticsSession.upload();
}
};
document.addEventListener("visibilitychange", onVisibilityChange, false);
app.onactivated = function (args) {
if (args.detail.kind === activation.ActivationKind.launch) {
if (args.detail.previousExecutionState !== activation.ApplicationExecutionState.terminated) {
// TODO: This application has been newly launched. Initialize
// your application here.
} else {
// TODO: This application has been reactivated from suspension.
// Restore application state here.
}
args.setPromise(WinJS.UI.processAll());
var sampleButton = document.getElementById("sampleButton");
sampleButton.addEventListener("click", eventButtonHandler, false);
// whenever the app is activated, initialize a localytics object.
var options = { logger: true, polling: false };
var localyticsSession = LocalyticsSession("871b4e162f27f37fb8db3b0-0dcd0bf8-d040-11e1-4668-00ef75f32667", options);
localyticsSession.open();
localyticsSession.upload();
}
};
app.oncheckpoint = function (args) {
// TODO: This application is about to be suspended. Save any state
// that needs to persist across suspensions here. You might use the
// WinJS.Application.sessionState object, which is automatically
// saved and restored across suspension. If you need to complete an
// asynchronous operation before your application is suspended, call
// args.setPromise().
};
function eventButtonHandler(eventId) {
var sampleInput = document.getElementById("sampleInput").value;
localyticsSession.tagEvent("Button pressed", { "User input": sampleInput });
}
app.start();
})();
default.html
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title>SampleLocalyticsApp</title>
<!-- WinJS references -->
<link href="//Microsoft.WinJS.1.0.RC/css/ui-dark.css" rel="stylesheet" />
<script src="//Microsoft.WinJS.1.0.RC/js/base.js"></script>
<script src="//Microsoft.WinJS.1.0.RC/js/ui.js"></script>
<!-- SampleLocalyticsApp references -->
<link href="/css/default.css" rel="stylesheet" />
<script src="/js/default.js"></script>
<script src="/js/localytics.js"></script>
</head>
<body>
<h1>This is a sample Localytics application</h1>
<p>Sample input field:</p>
<input id="sampleInput" type="text" value="Default value" />
<button id="sampleButton">Test Event</button>
</body>
</html>
Common Mistakes
Ready to ship? Check our list of common integration mistakes to ensure you get the best reporting experience possible.