I have some issue with Firebase Google Login, which is not working on Android with Cordova (it was working perfectly on Web). I have followed these instructions: https://firebase.google.com/docs/auth/web/cordova
I think the problem comes from firebase's dynamic link or the cordova-plugin-universal-link. Please help me i'm just a beginner in Firebase and Cordova. Thank you very much.
Here is my Dynamics link on firebase and my code:
My Dynamic link:
My Dynamic link image
My code on config.xml:
<universal-links>
<host name="https://rentlz.page.link/index" scheme="https" />
<host name="https://project-rental-5593e.firebaseapp.com/" scheme="https">
<path url="/__/auth/callback"/>
</host>
</universal-links>
<preference name="AndroidLaunchMode" value="singleInstance" />
<preference name="android-minSdkVersion" value="29" />
My javascript src:
<script src=" js/jquery.js"></script>
<script type="text/javascript" src="js/jquery.mobile-1.4.5.js"></script>
<script type="text/javascript" src="cordova.js"></script>
<script src="./bundle.js"></script>
<script type="text/javascript" src="/node_modules/firebase/firebase-app.js"></script>
<script type="text/javascript" src="/node_modules/firebase/firebase-analytics.js"></script>
<script type="text/javascript" src="/node_modules/firebase/firebase-auth.js"></script>
<script type="module" src="src/firebase.js"></script>
<script type="text/javascript" src="js/auth.js"></script>
<script type="text/javascript" src="js/database.js"></script>
My auth.js code:
$(document).on("vclick", "#login", SignIn);
$(document).on("vclick", "#logout", SignOut);
/**
* Handles the sign in button press.
*/
function SignIn() {
var provider = new firebase.auth.GoogleAuthProvider();
firebase.auth().signInWithRedirect(provider).then(function() {
return firebase.auth().getRedirectResult();
}).then(function(result) {
// This gives you a Google Access Token.
// You can use it to access the Google API.
var token = result.credential.accessToken;
// The signed-in user info.
var user = result.user;
// ...
}).catch(function(error) {
// Handle Errors here.
var errorCode = error.code;
var errorMessage = error.message;
});
firebase.auth().getRedirectResult().then(function(result) {
if (result.credential) {
// This gives you a Google Access Token.
// You can use it to access the Google API.
var token = result.credential.accessToken;
// The signed-in user info.
var user = result.user;
// ...
}
}).catch(function(error) {
// Handle Errors here.
var errorCode = error.code;
var errorMessage = error.message;
});
}
function SignOut() {
firebase.auth().signOut().then(function() {
// Sign-out successful.
}).catch(function(error) {
// An error happened.
});
}
function initApp() {
// Listening for auth state changes.
// [START authstatelistener]
firebase.auth().onAuthStateChanged(function(user) {
if (user) {
console.log(user.photoURL)
// User is signed in.
var displayName = user.displayName;
var photoURL = user.photoURL;
var uid = user.uid;
var providerData = user.providerData;
$("#login").hide();
$("#logout").show();
document.getElementById("userimg").setAttribute("src", photoURL);
document.getElementById("username").innerHTML = displayName;
$("#card").show();
$("#post-contain").show();
$("#login-contain").hide();
} else {
// User is signed out.
$("#login").show();
$("#card").hide();
$("#logout").hide();
$("#post-contain").hide();
$("#login-contain").show();
}
});
// [END authstatelistener]
}
window.onload = function() {
initApp();
};
Related
I am working on Ionic Mobile Application. After Creating Facebook Login button(Working fine) i want to get User data (Public profile and Email for my database.
My Index.html
<script src="lib/ionic/js/ionic.bundle.js"></script>
<script src="lib/angular-sanitize/angular-sanitize.min.js"></script>
<script src="js/ng-cordova.min.js"></script><script src="lib/ng-cordova-oauth/dist/ng-cordova-oauth.min.js"></script>
<!-- cordova script (this will be a 404 during development) -->
<script src="cordova.js"></script>
<!-- your app's js -->
<script src="js/app.js"></script>
<script src="js/services.js"></script>
<script src="js/controllers.js"></script>
Controller.js
.controller('login',['$scope','myService','$location','$state','$timeout',function($scope,myService,$location,$state,$timeout)
{
$scope.fbLogin = function ($cordovaOauth,$http) {
facebookLogin(window.cordovaOauth, window.http);
console.log(fbLogin);
}
}])
app.js
var app = angular.module('starter', ['ionic', 'starter.controllers','starter.services','ngSanitize', 'ngCordova', 'ngCordovaOauth']);
Please tell me where i am doing wrong.
And Sometimes i Get $cordovaOauth error.
Modular is not Injected.
function login(){
facebookLogin(window.cordovaOauth, window.http);
}
function facebookLogin($cordovaOauth, $http)
{
$cordovaOauth.facebook("1633195863589792", ["email", "public_profile"], {redirect_uri: "http://localhost/callback"}).then(function(result){
displayData($http, result.access_token);
}, function(error){
alert("Error: " + error);
});
}
function displayData($http, access_token)
{
$http.get("https://graph.facebook.com/v2.2/me", {params: {access_token: access_token, fields: "name,gender,location,picture", format: "json" }}).then(function(result) {
var name = result.data.name;
var gender = result.data.gender;
var picture = result.data.picture;
}, function(error) {
alert("Error: " + error);
});
}
i am getting the following error on my device when running it,where as it runs withour erron on browser and only one of my device and check all the devices but same problem
can any one help me
Uncaught TypeError: Object.keys called on non-object ionic.bundle.js:9110
Failed to load resource: net::ERR_CACHE_MISS https://cdn.auth0.com/client/cWQeRf3L4Ength5tIFSrPhrNPUHgO6yQ.js?t1439965186084
Uncaught Error: [$rootScope:infdig] 10 $digest() iterations reached. Aborting!
Watchers fired in the last 5 iterations: []
http://errors.angularjs.org/1.3.13/$rootScope/infdig?p0=10&p1=%5B%5D ionic.bundle.js:22980
// Ionic Starter App
// angular.module is a global place for creating, registering and retrieving Angular modules
// 'starter' is the name of this angular module example (also set in a <body> attribute in index.html)
// the 2nd parameter is an array of 'requires'
// 'starter.controllers' is found in controllers.js
angular.module('starter', ['ionic', 'ngCordova', 'starter.controllers','starter.directives', 'auth0',
'angular-storage',
'angular-jwt', 'ngFileUpload','ngResource','ngRoute'])
.config(['$httpProvider', function($httpProvider) {
$httpProvider.defaults.useXDomain = true;
$httpProvider.defaults.headers.common = 'Content-Type: application/json';
delete $httpProvider.defaults.headers.common['X-Requested-With'];
}
])
.config(function($compileProvider){
$compileProvider.imgSrcSanitizationWhitelist(/^\s*(https?|file|blob|cdvfile|content):|data:image\//);
})
.run(function($ionicPlatform) {
$ionicPlatform.ready(function() {
// Hide the accessory bar by default (remove this to show the accessory bar above the keyboard
// for form inputs)
if (window.cordova && window.cordova.plugins.Keyboard) {
cordova.plugins.Keyboard.hideKeyboardAccessoryBar(true);
}
if (window.StatusBar) {
// org.apache.cordova.statusbar required
StatusBar.styleDefault();
}
});
})
/*File factory for browse*/
.factory("$fileFactory", function($q) {
var File = function() { };
console.log("This is in file factory");
File.prototype = {
getParentDirectory: function(path) {
var deferred = $q.defer();
window.resolveLocalFileSystemURI(path, function(fileSystem) {
fileSystem.getParent(function(result) {
deferred.resolve(result);
}, function(error) {
deferred.reject(error);
});
}, function(error) {
deferred.reject(error);
});
return deferred.promise;
},
getEntriesAtRoot: function() {
var deferred = $q.defer();
console.log("This is in get Entries in root");
window.webkitrequestFileSystem(1, 0, function(fileSystem) {
var directoryReader = fileSystem.root.createReader();
directoryReader.readEntries(function(entries) {
deferred.resolve(entries);
}, function(error) {
deferred.reject(error);
});
}, function(error) {
deferred.reject(error);
});
return deferred.promise;
},
getEntries: function(path) {
var deferred = $q.defer();
window.resolveLocalFileSystemURI(path, function(fileSystem) {
var directoryReader = fileSystem.createReader();
directoryReader.readEntries(function(entries) {
deferred.resolve(entries);
}, function(error) {
deferred.reject(error);
});
}, function(error) {
deferred.reject(error);
});
return deferred.promise;
}
};
return File;
})
.factory('Post', function($resource) {
return $resource('http://104.155.192.54:8080/api/logins');
})
.config(function($compileProvider){
$compileProvider.imgSrcSanitizationWhitelist(/^\s*(https?|ftp|mailto|file|tel):/);
})
/*This is file browser in ionic */
.factory('Camera', ['$q', function($q) {
return {
getPicture: function(options) {
var q = $q.defer();
navigator.camera.getPicture(function(result) {
// Do any magic you need
q.resolve(result);
}, function(err) {
q.reject(err);
}, options);
return q.promise;
}
}
}])
.config(['$httpProvider', function($httpProvider) {
$httpProvider.defaults.useXDomain = true;
$httpProvider.defaults.headers.common = 'Content-Type: application/json';
delete $httpProvider.defaults.headers.common['*'];
}
])
.factory('merchantRegisterFactory', function($http) {
var urlBase = 'http://104.155.192.54:8080/api/merchantlogins';
var _loginService = {};
_loginService.getLogins = function() {
return $http.get(urlBase);
};
_loginService.saveLogin = function(login) {
console.log("This is factory is merchantlogins app.js save");
return $http.post(urlBase,login);
};
_loginService.updateLogin = function(login) {
return $http.put(urlBase, login);
};
_loginService.deleteLogin = function(id) {
return $http.delete(urlBase + '/' + id);
};
return _loginService;
})
.factory('addOffer', function($http) {
var urlBase = 'http://104.155.192.54:8080/api/addoffers';
var _addofferService = {};
_addofferService.getOffers = function() {
return $http.get(urlBase);
};
_addofferService.saveOffer = function(login) {
console.log("This is factory is addoffers app.js save");
return $http.post(urlBase,login);
};
_addofferService.updateoffer = function(login) {
return $http.put(urlBase, login);
};
_addofferService.deleteOffer = function(id) {
return $http.delete(urlBase + '/' + id);
};
return _addofferService;
})
.factory('loginsFactory', function($http) {
var urlBase = 'http://104.155.192.54:8080/api/logins';
var _loginService = {};
_loginService.getLogins = function() {
return $http.get(urlBase);
};
_loginService.saveLogin = function(login) {
console.log("This is factory Login is app.js save");
return $http.post(urlBase,login);
};
_loginService.updateLogin = function(login) {
return $http.put(urlBase, login);
};
_loginService.deleteLogin = function(id) {
return $http.delete(urlBase + '/' + id);
};
return _loginService;
})
.run(function($rootScope, auth, store, jwtHelper, $location) {
// This events gets triggered on refresh or URL change
var refreshingToken = null;
$rootScope.$on('$locationChangeStart', function() {
var token = store.get('token');
var refreshToken = store.get('refreshToken');
if (token) {
if (!jwtHelper.isTokenExpired(token)) {
if (!auth.isAuthenticated) {
auth.authenticate(store.get('profile'), token);
}
} else {
if (refreshToken) {
if (refreshingToken === null) {
refreshingToken = auth.refreshIdToken(refreshToken).then(function(idToken) {
store.set('token', idToken);
auth.authenticate(store.get('profile'), idToken);
}).finally(function() {
refreshingToken = null;
});
}
return refreshingToken;
} else {
$location.path('/login');
}
}
}
});
})
.config(function($stateProvider, $urlRouterProvider, authProvider, $httpProvider,
jwtInterceptorProvider) {
jwtInterceptorProvider.tokenGetter = function(store, jwtHelper, auth) {
var idToken = store.get('token');
var refreshToken = store.get('refreshToken');
// If no token return null
if (!idToken || !refreshToken) {
return null;
}
// If token is expired, get a new one
if (jwtHelper.isTokenExpired(idToken)) {
return auth.refreshIdToken(refreshToken).then(function(idToken) {
store.set('token', idToken);
return idToken;
});
} else {
return idToken;
}
}
$httpProvider.interceptors.push('jwtInterceptor');
$stateProvider
.state('app', {
url: "/app",
abstract: true,
templateUrl: "templates/menu.html",
controller: 'AppCtrl'
})
.state('app.addoffer', {
url: "/addoffer",
views: {
'menuContent': {
templateUrl: "templates/addoffer.html",
controller: 'MapCtrl'
}
}
})
.state('app.browse', {
url: "/browse",
views: {
'menuContent': {
templateUrl: "templates/browse.html"
}
}
})
.state('app.playlists', {
cache: false,
url: "/playlists",
views: {
'menuContent': {
templateUrl: "templates/playlists.html",
controller: 'ExampleController'
}
}
})
.state('app.single', {
cache: false,
url: "/playlists/:playlistId",
views: {
'menuContent': {
templateUrl: "templates/playlist.html",
controller: 'ExampleController'
}
}
});
authProvider.init({
domain: 'lokaloffers.auth0.com',
clientID: 'cWQeRf3L4Ength5tIFSrPhrNPUHgO6yQ',
loginState: 'login'
});
// if none of the above states are matched, use this as the fallback
$urlRouterProvider.otherwise('/app/playlists');
})
.run(function(auth) {
// This hooks all auth events to check everything as soon as the app starts
auth.hookEvents();
});
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="initial-scale=1, maximum-scale=1, user-scalable=no, width=device-width">
<meta http-equiv="Content-Security-Policy" content="default-src *; style-src * 'unsafe-inline'; script-src * 'unsafe-inline' 'unsafe-eval'">
<title></title>
<!-- compiled css output -->
<link href="css/ionic.app.css" rel="stylesheet">
<link href="css/animate.css" rel="stylesheet">
<link href="lib/ionic/css/ionic.css" rel="stylesheet">
<link href="css/style.css" rel="stylesheet">
<!-- IF using Sass (run gulp sass first), then uncomment below and remove the CSS includes above -->
<!-- <link href="css/ionic.app.css" rel="stylesheet">-->
<!-- ionic/angularjs js -->
<script type="text/javascript" src="lib/ionic/js/ionic.bundle.js"></script>
<!-- ngCordova script -->
<script type="text/javascript" src="lib/ngCordova/dist/ng-cordova.js"></script>
<script type="text/javascript" src="cordova.js"></script>
<script type="text/javascript" src="lib/angular-resource/angular-resource.js"></script>
<script type="text/javascript" src="lib/ng-file-upload/ng-file-upload-shim.min.js"></script>
<script type="text/javascript" src="lib/ng-file-upload/ng-file-upload.min.js"></script>
<!-- Auth0 Lock -->
<script type="text/javascript" src="lib/auth0-lock/build/auth0-lock.js"></script>
<!-- auth0-angular -->
<script type="text/javascript" src="lib/auth0-angular/build/auth0-angular.js"></script>
<!-- angular storage -->
<script type="text/javascript" src="lib/a0-angular-storage/dist/angular-storage.js"></script>
<!-- angular-jwt -->
<script type="text/javascript" src="lib/angular-jwt/dist/angular-jwt.js"></script>
<!--
<script src="https://maps.googleapis.com/maps/api/js?key=AIzaSyCqGXcExPSUxrVMpnfBciUejJRU06ZYelE&sensor=true"></script>
<script src="https://maps.googleapis.com/maps/api/js?v=3.exp&libraries=places&signed_in=true"></script>
<script src="https://maps.googleapis.com/maps/api/js?key=AIzaSyC_cy8C8pj5urqUSWERE-qU8NmkoNg6jpk&sensor=true"></script>
-->
<!-- your app's js -->
<script type="text/javascript" src="js/app.js"></script>
<script type="text/javascript" src="js/app1.js"></script>
<script type="text/javascript" src="js/directives.js"></script>
<script type="text/javascript" src="lib/angular-route/angular-route.min.js"></script>
<script type="text/javascript" src="lib/angular-route/angular-route.js"></script>
<script type="text/javascript" src="js/app.js"></script>
<script type="text/javascript" src="js/factory.js"></script>
<script type="text/javascript" src="js/controllers.js"></script>
<script type="text/javascript" src="js/countries.js"></script>
<script type="text/javascript" charset="utf-8">
// Wait for Cordova to load
//
document.addEventListener("deviceready", onDeviceReady, false);
// Cordova is loaded and it is now safe to make calls Cordova methods
//
function onDeviceReady() {
checkConnection();
}
function checkConnection() {
var networkState = navigator.connection.type;
var states = {};
states[Connection.UNKNOWN] = 'Unknown connection';
states[Connection.ETHERNET] = 'Ethernet connection';
states[Connection.WIFI] = 'WiFi connection';
states[Connection.CELL_2G] = 'Cell 2G connection';
states[Connection.CELL_3G] = 'Cell 3G connection';
states[Connection.CELL_4G] = 'Cell 4G connection';
states[Connection.NONE] = 'No network connection';
alert('Connection type: ' + states[networkState]);
}
</script>
</head>
<body ng-app="starter">
<ion-nav-view></ion-nav-view>
</body>
</html>
HI Thanks for the suggession but i solved my problem its the error with ionic CLI ,updated it to latest and it works fine
I've an hybrid app for android, i'm using cordova and onsen + angular js.
This is my index.html file:
<html lang="en" ng-app="AppModel">
<head>
<meta charset="utf-8">
<meta name="apple-mobile-web-app-capable" content="yes">
<meta name="mobile-web-app-capable" content="yes">
<title>AppModel</title>
<!-- <link rel="stylesheet" href="css/plugins.css"/> -->
<link rel="stylesheet/less" href="css/plugins.less"/>
<link rel="stylesheet" href="lib/onsen/css/onsenui.css">
<link rel="stylesheet" href="lib/onsen/css/onsen-css-components.css">
<link rel="stylesheet/less" href="css/app.less"/>
<link rel="stylesheet/less" href="css/base-layout.less"/>
<script src="css/less.min.js" type="text/javascript"></script>
<script src="http://maps.google.com/maps/api/js"></script>
<script src="js/lodash_3.2.0.min.js"></script>
<script src="lib/onsen/js/angular/angular.js"></script>
<script src="js/angular-google-maps_2.0.12.min.js"></script>
<script src="lib/onsen/js/angular/angular-touch.js"></script>
<script src="lib/onsen/js/onsenui.min.js"></script>
<script src="js/jquery.min.js"></script>
<script src="js/plugins.js"></script>
<script type="text/javascript" src="cordova.js"></script>
<script src="js/appStart.js"></script>
<script src="js/data/data.js"></script>
<script src="js/angularApp/controllers.js"></script>
<script src="js/angularApp/directives.js"></script>
<script src="js/angularApp/filters.js"></script>
</head>
<body >
<ons-sliding-menu
menu-page="modules/core/menu.html" main-page="modules/account_profile/login.html" side="left"
var="menu" type="reveal" max-slide-distance="260px" swipable="true" swipe-target-width="50">
</ons-sliding-menu>
</body>
</html>
This is the appStart.js
var app = {
// Application Constructor
initialize: function() {
this.bindEvents();
},
// Bind Event Listeners
//
// Bind any events that are required on startup. Common events are:
// 'load', 'deviceready', 'offline', and 'online'.
bindEvents: function() {
document.addEventListener('deviceready', this.onDeviceReady, false);
},
// deviceready Event Handler
//
// The scope of 'this' is the event. In order to call the 'receivedEvent'
// function, we must explicity call 'app.receivedEvent(...);'
exitFunction : function(){
if (navigator.notification.confirm("Vuoi chiudere l'app?",
function(index) {
if (index == 1) { // OK button
navigator.app.exitApp(); // Close the app
}
},
"AppModel",
["Ok","Annulla"]
));
},
onDeviceReady: function() {
app.receivedEvent('deviceready');
ons.setDefaultDeviceBackButtonListener(function() {
if (navigator.notification.confirm("Vuoi chiudere l'app?",
function(index) {
if (index == 1) { // OK button
navigator.app.exitApp(); // Close the app
}
},
"AppModel",
["Ok","Annulla"]
));
});
/*
// Open any external link with InAppBrowser Plugin
$(document).on('click', 'a[href^=http], a[href^=https]', function(e){
e.preventDefault();
var $this = $(this);
var target = $this.data('inAppBrowser') || '_blank';
window.open($this.attr('href'), target);
});
*/
$(document).on('click', 'a', function(e){
e.preventDefault();
var $this = $(this);
//var target = $this.data('inAppBrowser') || '_blank';
window.open($this.attr('href'), "_system");
});
},
// Update DOM on a Received Event
receivedEvent: function(id) {
//var parentElement = document.getElementById(id);
//var listeningElement = parentElement.querySelector('.listening');
//var receivedElement = parentElement.querySelector('.received');
//listeningElement.setAttribute('style', 'display:none;');
//receivedElement.setAttribute('style', 'display:block;');
console.log('Received Event: ' + id);
}
};
(function() {
var app = angular.module('AppModel', ['onsen', 'angular-carousel', 'uiGmapgoogle-maps'])
.config( [
'$compileProvider',
function( $compileProvider )
{
$compileProvider.aHrefSanitizationWhitelist(/^\s*(https?|file|ftp|mailto|tel|geo):/);
}
]);
document.addEventListener('deviceready', function() {
angular.bootstrap(document, ['AppModel']);
}, false);
})
And data.js, controller.js, filter.js, directive.js are all like this:
var app = angular.module('AppModel'); //this is the first line in each file
app.factory('MenuData', function(){ [...]
But when i launch the app in google chrome, the console says:
Uncaught Error: [$injector:nomod] Module 'AppModel' is not available! You either misspelled the module name or forgot to load it. If registering a module ensure that you specify the dependencies as the second argument.
http://errors.angularjs.org/1.2.10/$injector/nomod?p0=AppModel
This message appears for the files data.js, controller.js, filter.js, directives.js due to the first line of each file.
I don't know what to do. Can someone help me?
Doesn't look like you're executing the line where the app module is created.
You must run the line
angular.module('appName', [dependencies]);
before you created your controllers and services, like the error message says.
Are you calling the anonymous function that creates the module? Just add an empty parenthesis and it should run:
(function() {
var app = angular.module(...
})();
As the error message says, you must specify the dependencies as the second argument. If none is needed, then pass an empty array.
change
var app = angular.module('AppModel'); //this is the first line in each file
to
var app = angular.module('AppModel', []); //this is the first line in each file
and run it again.
Additional information: https://docs.angularjs.org/api/ng/function/angular.module
I am having trouble receiving any type of callback for the push notifications plugin for phonegap build, I have included the plugin inside config.xml.
I have signed up to GCM and got my project number needed for pushNotification.register().
I also have access to the window.plugins.pushNotification object so I know it's included the plugin.
PhoneGap Build Version: 3.1
Hydration: Disabled
Debug: Enabled
Device: Samsung Tab 2
My index.html js files included are:
<script type="text/javascript" src="phonegap.js"></script>
<script type="text/javascript" src="PushNotification.js"></script>
<script type="text/javascript" src="js/lib/jquery.js" ></script>
<script type="text/javascript" src="js/lib/handlebars.js"></script>
<script type="text/javascript" src="js/handlebars/helpers.js"></script>
<script type="text/javascript" src="js/plugins/fastclick.js"></script>
<script type="text/javascript" src="js/app.js"></script>
My config.xml plugins included are:
// plugins
<gap:plugin name="org.apache.cordova.console" />
<gap:plugin name="org.apache.cordova.device" />
<gap:plugin name="org.apache.cordova.geolocation" />
<gap:plugin name="org.apache.cordova.dialogs" />
<gap:plugin name="org.apache.cordova.inappbrowser" />
<gap:plugin name="org.apache.cordova.splashscreen" />
<gap:plugin name="com.phonegap.plugins.pushplugin" />
// access to external domains
<access origin="*"/>
My app.js call to pushNotification.register()
var app = {
init: function() {
document.addEventListener("deviceready", this.onDeviceReady, false);
},
onDeviceReady: function(){
// DO STUFF
// ....
// ENABLE PUSH
this.push_init();
},
push_init: function(){
app.SENDER_ID = 123456789; // replaced by my actual GCM project no
var pushNotification = window.plugins.pushNotification;
pushNotification.register(
function(){alert('Push: win');}, // never called
function(){alert('Push: Error');}, // never called
{ senderID: app.SENDER_ID, ecb: "app.push_android" }
);
},
// never called
push_android: function(e){
alert('connection established...');
console.log( 'successfully started android' );
console.log( e );
}
};
// start the app
app.init();
After that is called nothing is executed, app.push_android() is a function of app object.
If i don't enter a senderID I get an error saying no sender ID so I know that something is working. This is so frustrating any ideas?
PS - I also noticed something weird, when I console.log the window.plugins.pushNotification it returns an empty object, however I can still call window.plugins.pushNotification.register(), but I thought I would be visible inside the console.log.
I think I've found the solution.
I was passing an integer instead of a string for the property senderID in the object
Doesnt work
pushNotification.register(
function(){alert('Push: win');}, // NOT called
function(){alert('Push: Error');}, // NOT called
{ senderID: 123456789, ecb: "app.push_android" }
);
DOES work
pushNotification.register(
function(){alert('Push: win');}, // called
function(){alert('Push: Error');}, // called
{ senderID: "123456789", ecb: "app.push_android" }
);
Try this push notification code -
var pushNotification;
document.addEventListener('deviceready', onDeviceReady, true);
function onDeviceReady() {
try {
pushNotification = window.plugins.pushNotification;
if (device.platform == 'android' || device.platform == 'Android') {
pushNotification.register(successHandler, errorHandler, { "senderID": "123456789", "ecb": "onNotificationGCM" }); // required!
}
else {
pushNotification.register(tokenHandler, errorHandler, { "badge": "true", "sound": "true", "alert": "true", "ecb": "onNotificationAPN" }); // required!
}
}
catch (err) {
txt = "There was an error on this page.\n\n";
txt += "Error description: " + err.message + "\n\n";
alert(txt);
}
};
// handle GCM notifications for Android
function onNotificationGCM(e) {
switch (e.event) {
case 'registered':
if (e.regid.length > 0) {
alert(e.regid);
storeToken(e.regid);
}
break;
case 'message':
if (e.foreground) {
var my_media = new Media("beep.wav");
my_media.play();
}
else {
// otherwise we were launched because the user touched a notification in the notification tray.
}
break;
case 'error':
break;
default:
break;
}
}
Refer Link
Refer Devgirl's Weblog
I'm learning Android development with PhoneGap and Facebook Javascript SDK. I keep on having this error everytime I launch my application and I don't know exactly what's wrong. Could you please help me?
These are the following details :
Project Location :
D:\Android Dream\FacebookExercise\assets\www\index.html
Localhost Location :
C:\Program Files\Apache Software Foundation\Tomcat 7.0\webapps\ROOT\
I'm very sure my APP_ID is correctly set. These are some settings of my FB :
Website with Facebook Login
Site URL: http://localhost:8080/
Mobile Web
Mobile Site URL: http://localhost:8080/
index.html
<html>
<header>
<title>Kissa Android App</title>
<script type="text/javascript" charset="utf-8" src="cordova-2.5.0.js"></script>
<script type="text/javascript" src="http://connect.facebook.net/en_US/all.js"></script>
</header>
<body>
<div id="fb-root"></div>
<div id="user-info"></div>
<script type="text/javascript">
var isLoaded = false;
// Additional JS functions here
window.fbAsyncInit = function() {
FB.init({
appId : 'The App ID', // App ID
channelUrl : 'http://localhost:8080/res/channel.html', // Channel File
//channelUrl : 'http://10.0.2.2:8080/assets/www/channel.html',
status : true, // check login status
cookie : true, // enable cookies to allow the server to access the session
xfbml : true, // parse XFBML
oauth : true
});
isLoaded = true;
FB.getLoginStatus(function(response) {
if (response.status === 'connected') {
//window.location = "http://www.google.com";
} else if (response.status === 'not_authorized') {
// not_authorized
//alert("You are unauthorized to access this page.");
} else {
//document.getElementById('name').innerHTML = '';
}
});
FB.login(function(response) {
if (response.authResponse) {
FB.api('/me', function(response) {
document.getElementById('name').innerHTML = 'Name : ' + response.first_name;
var fbLoginBtn = document.getElementById('fbLoginBtn');
fbLoginBtn.innerHTML = '<fb:login-button autologoutlink="true" perms="email"> </fb:login-button>';
FB.XFBML.parse(fbLoginBtn);
});
} else {
// cancelled
}
});
FB.Event.subscribe("auth.logout", function() {window.location = 'index.html'});
};
// 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>
<script type="text/javascript">
function isLoaded(){
alert("heuy!");
if(isLoaded)
alert(isLoaded);
else
alert(isLoaded);
}
</script>
<fb:login-button autologoutlink="true" perms="email"> </fb:login-button>
<div id="fbLoginBtn">
<fb:login-button autologoutlink="true" perms="email"> </fb:login-button>
</div>
<div id="name" style="font-family : arial"></div>
<div id="email"></div>
<input type="button" onclick="isLoaded()" value="hey"/>
</body>
You cannot simply use the JS SDK in phonegap environment. You have to use the phonegap facebook plugin, which provides the same api. I have just wrote a little tutorial... http://pjsdev.blogspot.de/2013/03/phonegap-build-facebook-connect-part-2.html