Question

Lior Erez on Mon, 04 Jan 2016 19:55:20


I'm trying to use Cordova app insights plugin on my android app and I'm having a problem with the appInsights object on JavaScript. After installing the sample app in the github repository at https://github.com/MSOpenTech/cordova-plugin-ms-appinsights the appInsights object was defined and working, but when I took the exact same steps described in the readme in my application, I got an error "appInsights object undefined". 

I reviewed the code in the sample app and noticed that the appInsights object is a global object, but I couldn't find where this object was initialized.

When I tried to use that object on my app the error occurred.

How can I initialize the global object manually or make it work on my app?

Thanks in advance




Sponsored



Replies

Gary Liu - MSFT on Tue, 05 Jan 2016 02:45:41


Refer to the sample at the index.js of https://github.com/MSOpenTech/cordova-plugin-ms-appinsights/blob/master/sample/js/index.js, I tried to put the sample code at https://github.com/MSOpenTech/cordova-plugin-ms-appinsights#sample-usage into the bindEvents function closure, and it worked fine without the "appInsights object undefined" error. 

About the appInsights initialization, I dived into plugin file at /plugins/cordova-plugin-ms-appinsights/www/AppInsights.lib.js, format the code and found the function to initialize appInsights:

function initializeAppInsights() {
	var n, r;
	if (typeof window != "undefined" && typeof JSON != "undefined")
		if (n = "appInsights", window[n] === undefined) Microsoft.ApplicationInsights.AppInsights.defaultConfig = Microsoft.ApplicationInsights.Initialization.getDefaultConfig();
		else {
			var u = window[n] || {},
				t = new Microsoft.ApplicationInsights.Initialization(u),
				i = t.loadAppInsights();
			for (r in i) u[r] = i[r];
			t.emptyQueue();
			t.pollInteralLogs(i)
		}
}

And at the end of the file, it invokes the function as 

initializeAppInsights();

So if you need to manually initialize the object, you can try to remove the initializeAppInsights(); at AppInsights.lib.js file and invoke initializeAppInsights() at the place you want. For example in my test:

var app = {
    // Application Constructor
    initialize: function () {
        initializeAppInsights();
        document.addEventListener('deviceready', function () {
            app.bindEvents();
            app.onDeviceReady();
        });
    },
    ...
}