Can't get Dan Wilson's Google Analytics plugin to work - angularjs

What i am doing wrong? What else is required? I have added the Android platform to my app which I am importing in Android Studio and launching the app. But I cannot see any change in the Analytics dashboard.
plugin :- cordova plugin add cordova-plugin-google-analytics [having cordova 5.0+]
app.js
$ionicPlatform.ready(function() {
document.addEventListener("deviceready", onDeviceReady, false);
function onDeviceReady() {
window.plugins.sim.getSimInfo(successCallback, errorCallback);
}
function successCallback(result) {
console.log(result);
}
function errorCallback(error) {
console.log(error);
}
// Android only: check permission
function hasReadPermission() {
window.plugins.sim.hasReadPermission(successCallback, errorCallback);
}
// Android only: request permission
function requestReadPermission() {
window.plugins.sim.requestReadPermission(successCallback, errorCallback);
}
if (window.cordova && window.cordova.plugins.Keyboard) {
cordova.plugins.Keyboard.hideKeyboardAccessoryBar(true);
}
if(ionic.Platform.isWebView()){
var device_name = device.name,
device_version = device.version,
device_platform = device.platform;
if (typeof analytics !== "undefined") {
analytics.startTrackerWithId('UA-XXXXX-X'); // security purpose cannot give tracker_ID.
analytics.trackView('home');// tracking home page
analytics.trackView('partsearch'); //tracking part search page
analytics.trackView('aggregates');// tracking aggregate page
analytics.trackEvent("Affiliate", "Search");// check end of the code
console.log("Starting Analytics");
} else {
console.log("Google Analytics plugin could not be loaded.")
}
}
}
home.html
<div on-touch = "onTouchSearch()" style="text-align:center;height:105px;padding:5px;vertical-align:middle;" class="waves-effect waves-light no-margin" on-click="_gaq.push(['_trackEvent','Affiliate','Search']);">
//when search button is clicked on my app i want to see it in my google analytics dashboard

Related

response.redirect() is not working in express (NodeJS)

I want redirect to dashboard.html from login.html if username is correct, if not then alert box will be shown, I used both express response.redirect('path') or response.sendFile('path') but none is working here.
I am using angularJs as front-end and express module of nodeJs in back-end.
Express route code:
module.exports = function(app,db,path){
app.post('/student-login', function (request, response) {
var user = request.body;
if(user.username == "abhinav")
{
response.redirect('/views/dashboard.html');
response.end();
}
else{
response.send("Wrong username");
response.end();
}
});
}
AngularJs code:
angular.module('loginService',[])
.service('loginService',function($http){
return {
sendStudent : function(data){
return $http.post('/student-login',data)
.then(function(response){
return response.data;
});
}
}
});
AngularJs controller Code:
if ($scope.myForm.$valid)
loginService.sendStudent($scope.studentData)
.then(function(data){
if(data=="Wrong username")
alert(data);
});
Developer option > Network :
As you can see in the Network tab, browser does make a request to the /views/dashboard.html route. It means that redirect is working. The reason why you don't get the expected behavior is because you need to navigate to that page (right now you are simply loading content of the page).
I would suggest moving redirection logic from express to frontend and using http status codes to signal login errors.
Express code:
module.exports = function(app,db,path){
app.post('/student-login', function (request, response) {
var user = request.body;
if (user.username == "abhinav") {
response.sendStatus(200);
} else {
response.sendStatus(401);
}
});
}
AngularJS controller code:
if ($scope.myForm.$valid) {
loginService.sendStudent($scope.studentData).then(() => {
// login successful, response status is 200
location.href = '/views/dashboard.html'
}).catch(response => {
if (response.status === 401) {
alert("Wrong username")
} else {
alert("Some other error")
}
})
}
I'm using location.href as an example only because I'm not familiar with angularjs routing. It will reload the whole page, use API provided by angularjs router if you want to avoid that.

Adding google plus login to ionic app

I am trying to add google plus login to my ionic app.
Following this link gives me an error.
https://ionicthemes.com/tutorials/about/google-plus-login-with-ionic-framework
Error is : cannot read property googleplus of undefined.
Here is my app.js:
.run(function($ionicPlatform) {
$ionicPlatform.ready(function() {
if (window.cordova && window.cordova.plugins.Keyboard) {
cordova.plugins.Keyboard.hideKeyboardAccessoryBar(true);
cordova.plugins.Keyboard.disableScroll(true);
}
if (window.StatusBar) {
// org.apache.cordova.statusbar required
StatusBar.styleDefault();
}
});
})
Steps to Configure authentication in Device(android)
ionic start newApp
ionic platform add android
cordova plugin add cordova-plugin-inappbrowser
bower install ngCordova
bower install ng-cordova-oauth -S
include both script into index.html above cordova.js
<script src="lib/ngCordova/dist/ng-cordova.min.js"></script>
<script src="lib/ng-cordova-oauth/dist/ng-cordova-oauth.js"></script>
<script src="cordova.js"></script>
Dependency injection
include below code
$scope.googleLogin = function() {
console.log('In My Method');
$cordovaOauth.google("Client ID", ["https://www.googleapis.com/auth/urlshortener", "https://www.googleapis.com/auth/userinfo.email"]).then(function(result) {
console.log(JSON.stringify(result));
// results
}, function(error) {
// error
console.log('In Error');
console.log(error);
});
}
add button to view file and call the function
1 first add inappbrower in your app
2 create app id for google console
https://console.developers.google.com
a: create new project
b: click on Credentials
c: choose web application
d: set redirect path
if u have if not than set http://localhost/callback
e: click on create button
than a pop up appear save those id
after that add following code
NOTE:Please change your app id and secret id in code
$scope.loginGoogle = function() {
var requestToken = '';
var accessToken = '';
var clientId = '1018908884240-futc1bfc681kl2jegi3a7nn1m28aem1o.apps.googleusercontent.com';
var clientSecret = 'KRQGDwu_llvagUucKM9oLZ7I';
var deferred = $q.defer();
$cordovaOauth.google(clientId, ['email']).then(function(result) {
$localStorage.accessToken = result.access_token;
deferred.resolve(result.access_token);
$http.get('https://www.googleapis.com/oauth2/v1/userinfo?alt=json&access_token=' + $localStorage.accessToken, {
params: {
format: 'json'
}
}).then(function(result) {
console.log(JSON.stringify(result));
var id =result.data.id;
deferred.resolve(result.data);
}, function(error) {
deferred.reject({
message: 'here was a problem getting your profile',
response: error
});
});
}, function(error) {
deferred.reject({
message: 'There was a problem signing in',
response: error
});
});
}
Try to add <script src="cordova.js"></script> to your index.html file.
And Cordova plugins only runs on emulators or real devices. try Ripple Emulator if you want to test it in a browser.
Credit to Cordova plugins not working with ionic

Cordova InAppBrowser show location bar Cordova AngularJS Oauth

Hi I'm using the Cordova InAppBrowser and AngularJS Oauth plugins.
When I press a normal link button like this:
<a class="external" ng-href="https://www.website.com/" targe="_blank" >open link</a>
In combination with this:
<script>
$( document ).ready(function() {
// open links in native browser (phonegap);
$(document).on('click', '.external', function (event) {
event.preventDefault();
window.open($(this).attr('href'), '_blank');
return false;
});
});
</script>
It opens the link in the in app browser. In the InAppBrowser when loading the url it is showing the url location at the bottom. So this is working OK.
When the AngularJS Oauth plugin opens the InAppBrowser and starts to load the login page of Facebook for example it doesn't show the loading url location at the bottom.
I tried to add "location=yes" in the Oauth plugin like this, but it is still not showing the url loading bar at the bottom:
window.open('https://www.website.com/oauth/authorize?client_id=' + clientId + '&redirect_uri=http://localhost/callback&scope=' + appScope.join(",") + '&response_type=code&approval_prompt=force', '_blank', 'location=yes,clearsessioncache=yes,clearcache=yes');
How can I force to show the loading bar with Oauth in the InAppBrowser ?
The reason I want this is when a login page needs some time to load there is no loading indication and you mind think there is nothing happening.
This is how the Oauth function looks like with location=yes:
strava: function(clientId, clientSecret, appScope) {
var deferred = $q.defer();
if(window.cordova) {
var cordovaMetadata = cordova.require("cordova/plugin_list").metadata;
if(cordovaMetadata.hasOwnProperty("cordova-plugin-inappbrowser") === true || cordovaMetadata.hasOwnProperty("org.apache.cordova.inappbrowser") === true) {
var browserRef = window.open('https://www.strava.com/oauth/authorize?client_id=' + clientId + '&redirect_uri=http://localhost/callback&scope=' + appScope.join(",") + '&response_type=code&approval_prompt=force', '_blank', 'location=yes,clearsessioncache=yes,clearcache=yes');
browserRef.addEventListener('loadstart', function(event) {
if((event.url).indexOf("http://localhost") === 0) {
requestToken = (event.url).split("code=")[1];
$http.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded';
$http({method: "post", url: "https://www.strava.com/oauth/token", data: "client_id=" + clientId + "&client_secret=" + clientSecret + "&code=" + requestToken })
.success(function(data) {
deferred.resolve(data);
})
.error(function(data, status) {
deferred.reject("Problem authenticating");
})
.finally(function() {
setTimeout(function() {
browserRef.close();
}, 10);
});
}
});
browserRef.addEventListener('exit', function(event) {
deferred.reject("The sign in flow was canceled");
});
} else {
deferred.reject("Could not find InAppBrowser plugin");
}
} else {
deferred.reject("Cannot authenticate via a web browser");
}
return deferred.promise;
},
I found the solution.
My app was loading the oauth plugin twice, once via a separate oauth script I added to my project and once via the ngCordova library. The ngCordova script was overruling the oauth script I added so that's why the location=yes was not working.
I removed the separate oauth script and changed location=no to yes in the ngCordova oauth script.

Facebook login on mobile via Cordova/Angular/Ionic

I'm working in a hybrid app to report potholes in our city.
The user can register to the app in a classic way (fill forms) or via one of the social networks (facebook, gmail, twitter).
The system works through a server on rails and a mobile app as a client(ionic/angular)
On the server side we have solved this, the user can make sign up / sign in to the page in the way that they want.
But with have several problems with the app, the app does nothing when you make click to the button of "sign in via facebook"
this is the style it is organized.
app/
plugins/
InAppBrowser
www/
css/
js/
controllers/
splash.js
map.js
tabs.js
services/
users.js
notifications.js
app.js
utils.js
lib/
angular/
ng-cordova-oauth/
ngCordova/
ionic/
templates/
map.html
splash.html
tabs.html
index.html
The splash.js controller is in charge of making the login function.
angular.module('app')
.controller('SplashCtrl', function($scope, User, $state, $ionicPopup, $auth, $cordovaOauth) {
$scope.session_id = User.session_id;
$scope.facebookLogin = function() {
alert("flag1");
User.fbSignIn().then(function() {
alert("flag2");
User.fbGetData().then(function() {
alert("flag3");
User.fbAuth().then(function() {
alert("flag4");
// Detect if it is a sign in or sign up
if (User.username) {
console.log('Controller reports successfull social login.');
$state.go('tab.map');
} else {
// Open finish signup modal
console.log('Contorller reports this is a new user');
$state.go('finish_signup');
}
}, function() {
alert("flag5");
$ionicPopup.alert({
title: '<b>App</b>',
template: 'Credenciales no vĂ¡lidas, vuelve a intentar.',
okText: 'Aceptar',
okType: 'button-energized'
})
});
}, function() {
alert("flag6");
// alert('Could not get your Facebook data...');
});
}, function() {
alert("flag7");
// alert('Could not sign you into Facebook...');
});
}
})
I put some alert flags through the functions to see where the app get stuck.
I can only see the 'flag1' alert on the phone.Then nothing happens
the controller communicates with the service users.js
I put the code on pastebin because it's too long
users.js service
The client must request an access token to the server and then compare in SplashCtrl if they got the token access the app redirects the user to tabs.html template that would be the main page.
The console server shows nothing. So the request application never communicates to the server. Eventhough the 'CLIENTS' and 'SERVER' variables are already declared in app.js
.constant('SERVER', {
url: 'https://rails-tutorial-denialtorres.c9.io'
})
.constant('CLIENTS', {
facebook: 'fb Api'
});
I can only logging of the server if I put a username and password in a traditional way
preview
I hope you can help me with this guys
regards and thanks!!
you try this ?
http://ngcordova.com/docs/plugins/oauth/
I tested and work very well, easy to implement, and also you can parse the json with token (and use server side if you need)
Remember this work ONLY with real device, not with Ionic Serve.
In case you looking for custom facebook login (javascript), try this code :
facebookStatus = function() {
var dfd = new jQuery.Deferred();
FB.getLoginStatus(function(response) {
if (response.status === 'connected') {
dfd.resolve({status: response.status, token: response.authResponse.accessToken});
} else if (response.status === 'not_authorized') {
// the user is logged in to Facebook, //but not connected to the app
dfd.resolve({status: response.status, token: false});
} else {
// the user isn't even logged in to Facebook.
FB.login(function(response) {
if (response.status=="connected"){
var token = response.authResponse.accessToken;
dfd.resolve({status: response.status, token: response.authResponse.accessToken});
}
}, {scope:'YOUR SCOPE HERE'});
}
});
return dfd.promise();
};
*Remember if you use this code, to add on index page the standard Facebook App details (something like)
<div id="fb-root"></div>
<script>
window.fbAsyncInit = function() {
FB.init({
appId : 'YOUR APP ID',
status : true, // check login status
cookie : false, // enable cookies to allow the server to access the session
xfbml : true // parse XFBML
});
};
// Load the SDK asynchronously
(function(d){
var js, id = 'facebook-jssdk', ref = d.getElementsByTagName('script')[0];
if (d.getElementById(id)) {return;}
js = d.createElement('script'); js.id = id; js.async = true;
js.src = "//connect.facebook.net/en_US/all.js";
ref.parentNode.insertBefore(js, ref);
}(document));
</script>
When I install the cordova plugin with add org.apache.cordova.inappbrowser
The id for the plugin is cordova-plugin-inappbrowser and the ngcordova.js library is looking for org.apache.cordova.inappbrowser
Changing those lines on ngcordova.js solves the issue.

FB.login() on iOS 6 doesn't return control to scripts with asynchronous execution

I've created Facebook Bug ID 517124631665353 to ask about this issue, but I'm not sure if it's a bug with Facebook's JS SDK or with the latest version of mobile Safari that comes with iOS 6. This only happens on iPhones and iPads running iOS 6.
Try each of these FB Rell examples:
Plain alert():
http://www.fbrell.com/saved/5224cbd2585cdcd4faefd2de236e577c
<button id="fb-login">Login & Permissions</button>
<script>
document.getElementById('fb-login').onclick = function() {
var cb = function(response) {
Log.info('FB.login callback', response);
if (response.status === 'connected') {
Log.info('User logged in');
} else {
Log.info('User is logged out');
}
alert('This fires on Mobile Safari, iOS 6.');
};
FB.login(cb, { scope: 'publish_actions' });
};
</script>
alert() in setTimeout():
http://www.fbrell.com/saved/9fee23e8553878748f8a3b840e8f0cb5
<button id="fb-login">Login & Permissions</button>
<script>
document.getElementById('fb-login').onclick = function() {
var cb = function(response) {
Log.info('FB.login callback', response);
if (response.status === 'connected') {
Log.info('User logged in');
} else {
Log.info('User is logged out');
}
setTimeout(function () {alert('This never fires on Mobile Safari, iOS 6.')}, 0);
};
FB.login(cb, { scope: 'publish_actions' });
};
</script>
On both iPads and iPhones running iOS 6, the alert() in a setTimeout() does not fire. On iPads, the popup window seems to close itself in all cases, but in iPhones, the popup window does not close, and only sometimes the user is returned to the original page.
We originally saw this problem on www.expertflyer.com/mobile, where we send off an AJAX request once the Facebook login is complete. We found that the code that should execute when that AJAX request returns is never executed. This is shown more simply using the setTimeout() call in the FB Rell example, but the commonality is that asynchronous code is not executed after the Facebook login returns. This was working previously, and we have not made any changes to our code, and this works as expected in earlier versions of iOS and on Android.

Resources