I'm in the middle of finalizing an Ionic 3 build and would like to add Google Analytics to it. I added it successfully and can see in GA (real time) that the app is being used however I would like to track all page/screen views. Does anyone know of way to do that?
I'm using the following plugin: https://github.com/danwilson/google-analytics-plugin
Here is the code I am using to initialize GA
initGoogleAnalytics() {
var trackingId = 'UA-114720506-2';
if (/(android)/i.test(navigator.userAgent)) { // for android
trackingId = 'UA-114720506-2';
} else if (/(ipod|iphone|ipad)/i.test(navigator.userAgent)) { // for ios
trackingId = 'UA-114720506-2';
}
//platform is injected in the Constructor
this.platform.ready().then(() => {
this.ga.debugMode();
this.ga.startTrackerWithId(trackingId).then(()=> {
console.log("GoogleAnalytics Initialized with ****** : " + trackingId);
this.ga.trackView('schedule');
this.ga.trackView('speakerList');
this.ga.trackView('map');
this.ga.trackView('social');
this.ga.trackView('exhibitors');
this.ga.enableUncaughtExceptionReporting(true)
.then((_success) => {
console.log("GoogleAnalytics enableUncaughtExceptionReporting Enabled.");
}).catch((_error) => {
console.log("GoogleAnalytics Error enableUncaughtExceptionReporting : " + _error)
});
});
});
}
Essentially adding in the GA Module and initializing with ionViewDidEnter on in every page that I wanted to track did the trick.
Related
I'm using Ionic4 and I'm trying to get the device battery level. But I get an error:
ERROR TypeError: Invalid event target
and for the battery level, I get undefined.
Has anyone run into the same problem
There is an open bug report at ionic: https://github.com/ionic-team/ionic-native/issues/2972
Unfortunately no solution yet, however there is a workaround to bypass the ionic typescript wrapper and just listen directly on the window events.
fromEvent(window, 'batterystatus').subscribe((status) => {
console.log(status)
});
This is how I managed to get the battery status in Ionic 4:
window.addEventListener('batterystatus', this.onBatteryStatus, false);
onBatteryStatus(status) {
console.log('Level: ' + status.level + ' isPlugged: ' + status.isPlugged);
}
An easy way could be like this:
$ ionic cordova plugin add cordova-plugin-battery-status
$ npm install --save #ionic-native/battery-status#4
Then in your code:
import { Platform } from 'ionic-angular';
import { BatteryStatus } from '#ionic-native/battery-status';
batterylevel = 0;
constructor(...
private batteryStatus: BatteryStatus,
private plt: Platform ) {}
ionViewDidEnter()
{
// Cordova check
if(this.plt.is('core') || this.plt.is('mobileweb'))
{
// NO. It's a browser.
// don't call the batery.
}
else
{
const batterysubscription = this.batteryStatus.onChange().subscribe(status => {
this.batterylevel = status.level;
});
}
}
yourfunction()
{
console.log(this.batterylevel);
}
You'll also need to add it to your provider list too.
Of course, this will only work in emulation or a device.
I am investigating using Ionic 4/ Capacitor to target Windows via the Electron option, for an application where I want to use SQLite.
Using the Ionic Native SQLite plugin, which wraps this Cordova plugin, out of the box, as far as I can see, the Windows support is for UWP, and not Desktop, which runs using Electron in Ionic Capacitor wrapper.
My plan, was to see if I could use Electron SQLite package, and then call this from my Ionic application by making a wrapper class for the Ionic native similar to what I used to get browser support by following this tutoral
If I can call the Electron code from my Ionic app, then I can't see why this wouldn't work.
So, my question here is, can I call code (I will add functions to use the SQlite) I add to the hosting Electron application from within the Ionic (web) code? And if so, how?
Thanks in advance for any help
[UPDATE1]
Tried the following...
From an Ionic page, I have a button click handler where I raise an event..
export class HomePage {
public devtools() : void {
let emit = new EventEmitter(true);
emit.emit('myEvent');
var evt = new CustomEvent('myEvent');
window.dispatchEvent(evt);
}
Then within the Electron projects index.js, I tried..
mainWindow.webContents.on('myEvent', () => {
mainWindow.openDevTools();
});
const ipc = require('electron').ipcMain
ipc.on('myEvent', (ev, arg) => {
mainWindow.openDevTools();
});
But neither worked.
I should mention I know very little about Electron. This is my first exposure to it (via Capacitor)
In case someone is interested, this is how I solved this.
Im am using Ionic 4 / Capacitor + Vue 3.
In my entry file (app.ts) I have declared a global interface called Window as follows:
// app.ts
declare global { interface Window { require: any; } }
Then, I have written the following class:
// electron.ts
import { isPlatform } from '#ionic/core';
export class Electron
{
public static isElectron = isPlatform(window, 'electron');
public static getElectron()
{
if (this.isElectron)
{
return window.require('electron');
}
else
{
return null;
}
}
public static getIpcRenderer()
{
if (this.isElectron)
{
return window.require('electron').ipcRenderer;
}
else
{
return null;
}
}
public static getOs()
{
if (this.isElectron)
{
return window.require('os');
}
else
{
return null;
}
}
}
And I use it like this:
//electronabout.ts
import { IAbout } from './iabout';
import { Plugins } from '#capacitor/core';
import { Electron } from '../utils/electron';
export class ElectronAbout implements IAbout
{
constructor() { }
public async getDeviceInfo()
{
let os = Electron.getOs();
let devInfo =
{
arch: os.arch(),
platform: os.platform(),
type: os.type(),
userInfo: os.userInfo()
};
return devInfo;
}
public async showDeviceInfo()
{
const devInfo = await this.getDeviceInfo();
await Plugins.Modals.alert({ title: 'Info from Electron', message: JSON.stringify(devInfo) });
}
}
This is working but, of course, I still need to refactor the Electron class (electron.ts). Probably using the singleton pattern is a better idea.
I hope this helps.
Update
You can communicate from the render process with your main process (index.js) like this:
//somefile.ts
if (Electron.isElectron)
{
let ipc = Electron.getIpcRenderer();
ipc.once('hide-menu-button', (event) => { this.isMenuButtonVisible = false; });
}
//index.js
let newWindow = new BrowserWindow(windowOptions);
newWindow.loadURL(`file://${__dirname}/app/index.html`);
newWindow.webContents.on('dom-ready', () => {
newWindow.webContents.send('hide-menu-button');
newWindow.show();
});
I dug into this yesterday and have an example for you using angular(this should apply to ionic too).
in your service declare require so we can use it
//Below your imports
declare function require(name:string);
Then in whatever function you want to use it in:
// Require the ipcRenderer so we can emit to the ipc to call a function
// Use ts-ignore or else angular wont compile
// #ts-ignore
const ipc = window.require('electron').ipcRenderer;
// Send a message to the ipc
// #ts-ignore
ipc.send('test', 'google');
Then in the created index.js within the electron folder
// Listening for the emitted event
ipc.addListener('test', (ev, arg) => {
// console.log('ev', ev);
console.log('arg', arg);
});
Its probably not the correct way to access it but its the best way i could find. From my understanding the ipcRenderer is used for when you have multiple browsers talking to each other within electron. so in our situation it enables our web layer to communicate with the electron stuff
I´m new to Ionic2, but experienced in web development. Just learning new platform at the moment.
So I have tried to integrate the Anyline OCR SDK
https://github.com/Anyline/anyline-ocr-cordova-module
but I am failing, it seems to me that the plugin is written in Javascript and not compatible with TS but I´m not sure...
Is there anyone out there that could help?
Thanks,
Ben
Not sure if you still need help with that, but for those out there who are looking for a working solution, here is mine:
1 - Add the Anyline Plugin to your project cordova plugin add io-anyline-cordova
2 - Create a new file ionic g provider anyline
3 - add this code to your anyline.ts file:
export class OCR {
constructor() {
if (anylineScan === undefined) {
var anylineScan = {};
}
}
anylineScan = {
onResult: function (result) {
console.log("MRZ result: " + JSON.stringify(result));
//do what you want here with the result
},
onError: function (error) {
console.log("scanning error");
},
scan: function () {
var licenseKey = "enterYourLicenceKeyHere";
try {
(<any>window).cordova.exec(this.onResult, this.onError, "AnylineSDK", "OCR", [licenseKey, {
"captureResolution":"1080p",
//your other config setting here
}]);
}
catch (e){
console.log("Cannot open scan view: ERROR occurred");
}
}
}
4 - Add the file references to your app.module.ts file
import { OCR } from '../yourFolderName/anyline';
...
providers: [Storage, OCR]
5 - In your page.ts file add the following call:
this.anyline.anylineScan.scan();
Important! It will not work in the browser, make sure you run ionic platform add ios (or android) and run the app on a device.
This should work!
Good luck and happy coding :-)
I found this code:
login() {
this.platform.ready().then(() => {
this.facebookLogin().then((success) => {
alert(success.access_token);
}, (error) => {
alert(error);
});
});
}
facebookLogin() {
return new Promise(function(resolve, reject) {
var browserRef = window.cordova.InAppBrowser.open("https://www.facebook.com/v2.0/dialog/oauth?client_id=" + "CLIENT_ID_HERE" + "&redirect_uri=http://localhost/callback&response_type=token&scope=email", "_blank", "location=no,clearsessioncache=yes,clearcache=yes");
browserRef.addEventListener("loadstart", (event) => {
if ((event.url).indexOf("http://localhost/callback") === 0) {
browserRef.removeEventListener("exit", (event) => {});
browserRef.close();
var responseParameters = ((event.url).split("#")[1]).split("&");
var parsedResponse = {};
for (var i = 0; i < responseParameters.length; i++) {
parsedResponse[responseParameters[i].split("=")[0]] = responseParameters[i].split("=")[1];
}
if (parsedResponse["access_token"] !== undefined && parsedResponse["access_token"] !== null) {
resolve(parsedResponse);
} else {
reject("Problem authenticating with Facebook");
}
}
});
browserRef.addEventListener("exit", function(event) {
reject("The Facebook sign in flow was canceled");
});
});
}
I am a bit confused, how does Ionic 2 app recognizes when user is signed in with some social apps like facebook/google?
For example, I want to make a landing page, which prompts for facebook login, and as soon as user is logged-in, dont show the page.
I am familiar with nodejs+passportjs which stores session/cookies, but how Ionic 2 it does?
You can use Ionic Native's NativeStorage plugin to store user preferences. It keeps the data until the app is uninstalled.
Find more about it here:
https://ionicframework.com/docs/v2/native/nativestorage/
There are different ways to integrate Facebook authentication Ionic app:
Implement any Facebook authentication using Javascript
CordovaOauth
etc.
Ionic Native
Ionic Native is a curated set of ES5/ES6/TypeScript wrappers for Cordova/PhoneGap plugins that make adding any native functionality you need to your Ionic, Cordova, or Web View mobile app easy.
- Facebook: http://ionicframework.com/docs/v2/native/facebook/
Page provides all details needed to implement native Facebook authentication in your Ionic app.
Hope this helps answering your question and concerns.
We are currently using the soundcloud API SDK for streaming and it does work on desktop but not 100% on mobile. (using responsive html. same api of course)
Sometime track is not lauch ? sometime it is.
I do not have specific error but on chrome network this line is show in red ??
http://api.soundcloud.com/tracks/146926142/stream?client_id=XXXXX
Redirect
We use a function to stream the track.
function streamTrack(id) {
var defer = $q.defer();
// Stream the track
SC.stream('/tracks/' + id, {
useHTML5Audio: false,
waitForWindowLoad: true,
onfinish: _scope.next,
whileplaying: function () {
var _this = this;
// Since we are in a callback, we need to tell angularJS to apply the change
if (timeout1) $timeout.cancel(timeout1);
timeout1 = $timeout(function () {
// Update the progress bar
_scope.progress = (_this.position / currentTrackDuration * 100) + '%';
_scope.timer = moment(_this.position).format('mm:ss');
$rootScope.$broadcast('trackRunning', { timerunning: _scope.timer });
});
}
}, function (sound) {
if (sound) {
defer.resolve(sound);
} else {
defer.reject();
}
});
return defer.promise;
}
If somebody has an idea pls.
Best Regards
Xavier