PhoneGap Build Push Notification (Android) - android

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

Related

Firebase Google Auth not working on Cordova Android

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();
};

Cordova Phonegap local notifications not working

I wanted to first say this is a really nice plugin (https://github.com/katzer/cordova-plugin-local-notifications) but having some difficulties getting it working.
I am using an Android and Phonegap CLI. I have tried both CLI 5.0 and now Phonegap 3.5.0, this is my config.xml:
<preference name="phonegap-version" value="3.5.0" />
In my config.xml I have tried all these combinations:
<plugin name="de.appplant.cordova.plugin.local-notification" spec="0.8.1" source="pgb" />
<gap:plugin name="de.appplant.cordova.plugin.local-notification" />
<plugin name="de.appplant.cordova.plugin.local-notification" source="pgb" />
However the notifications do not appear - nothing happens on the phone - nothing, nada, zilch. I have also downloaded the KitchenSink App (https://github.com/katzer/cordova-plugin-local-notifications/tree/example) and installed on Phonegap build and my phone and nothing again happens..
This is my code on index.html so when the phone fires it should register a local notification asap:
cordova.plugins.notification.local.registerPermission(function (granted) {
// console.log('Permission has been granted: ' + granted);
});
cordova.plugins.notification.local.schedule({
id: 1,
title: 'Reminder',
text: 'Dont forget to pray today.',
every: 'minute',
icon: 'res://icon',
smallIcon: 'res://ic_popup_sync'
});
I also tried
cordova.plugins.notification.local.schedule({
id: 2,
text: "Good morning!",
firstAt: tomorrow_at_8_am,
every: "day" // "minute", "hour", "week", "month", "year"
});
Even the KitchenSink app is not working - nothing happens on the phone??
My Android version is: 5.1.1
How can I get local notifications to appear in Phonegap?
I too have spent many hours trying to get this plugin working & I have, but i do find it to be one of the most temperamental.
Within your js -
var testNotifications = function () {
document.addEventListener("deviceready", function () {
console.warn("testNotifications Started");
// Checks for permission
cordova.plugin.notification.local.hasPermission(function (granted) {
console.warn("Testing permission");
if( granted == false ) {
console.warn("No permission");
// If app doesnt have permission request it
cordova.plugin.notification.local.registerPermission(function (granted) {
console.warn("Ask for permission");
if( granted == true ) {
console.warn("Permission accepted");
// If app is given permission try again
testNotifications();
} else {
alert("We need permission to show you notifications");
}
});
} else {
var pathArray = window.location.pathname.split( "/www/" ),
secondLevelLocation = window.location.protocol +"//"+ pathArray[0],
now = new Date();
console.warn("sending notification");
var isAndroid = false;
if ( device.platform === "Android" ) {
isAndroid = true;
}
cordova.plugin.notification.local.schedule({
id: 9,
title: "Test notification 9",
text: "This is a test notification",
sound: isAndroid ? "file://sounds/notification.mp3" : "file://sounds/notification.caf",
at: new Date( new Date().getTime() + 10 )
// data: { secret:key }
});
}
});
}, false);
};
Now on your html tag -
<button onclick="testNotifications()">Test notification</button>
That should trigger a notification or warn you that it needs permissions
Also top tip is to make sure your notifications are in a folder in the root of the project. android should be mp3 and ios caf
Answer 1 :for version 3.5.0
have a look at plugin's plugin.xml. see line 22
<engine name="cordova" version=">=3.6.0" />
that means plugin only supports version greater than 3.6.0 and you are using 3.5.0
Answer 2 :for version 5.0 or higher
Try the following code as index.html. if it runs perfectly then and other options in to notification.schedule.
as we haven't provided time(at) option notification will triggered immediately.
<html>
<script type="text/javascript" src="cordova.js"></script>
<script>
document.addEventListener('deviceready', onDeviceReady.bind(this), false);
function onDeviceReady() {
cordova.plugins.notification.local.schedule({
id: 1,
title: "Sample Notification",
text: "foo",
every: "week",
data: { meetingId: "123#fg8" }
});
};
</script>
<body>
</body>
</html>

Onsen - Cordova - AngularJs module is not available

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

Device is not defined error pops up when launching my Phonegap Push notification app

I used the example source code from (https://github.com/phonegap-build/PushPlugin/tree/master/Example/www). Problem is that, when I install my app and launch it my android phone (or android SDK emulator), it fails to register device to Android GCM. All the time error pops-up - "Device is not defined". I dont know exactly how I can catch error, why it fails to register device.
Steps that I preformed is:
– Created Phonegap project
– Installed following 3 plugins (cordova-plugin-device.git, cordova-plugin-media.git, PushPlugin).
– Registered App in Google Android GCM and retrieved my Goolge cloud API and Project Number
Locate the PushNotification.js file that was installed into my project-root/plugins folder. This file was copied into my project-root/www folder and referenced from the index.html
Added in my index file
Added to my www/config.xml file
Added JQuery mobile JS + CSS files to my project
Changed senderID in my HTML code:"1111146417746
Builded app with CLI - phonegap build android
And here is my Index.html code:
<html>
<head>
<title>com.PhoneGap.c2dm</title>
</head>
<body>
<!--<script type="text/javascript" charset="utf-8" src="cordova-2.2.0.js"></script>-->
<link rel="stylesheet" href="ext/jquery/jquery.mobile-min.css">
<script type="text/javascript" src="ext/jquery/jquery-min.js"></script>
<script type="text/javascript" src="ext/jquery/jquery.mobile-min.js"></script>
<script type="text/javascript" src="ext/jquery.qrcode.js"></script>
<script type="text/javascript" charset="utf-8" src="cordova.js"></script>
<script type="text/javascript" src="PushNotification.js"></script>
<script type="text/javascript">
var pushNotification;
function onDeviceReady() {
$("#app-status-ul").append('<li>deviceready event received</li>');
document.addEventListener("backbutton", function(e)
{
$("#app-status-ul").append('<li>backbutton event received</li>');
if( $("#home").length > 0)
{
// call this to get a new token each time. don't call it to reuse existing token.
//pushNotification.unregister(successHandler, errorHandler);
e.preventDefault();
navigator.app.exitApp();
}
else
{
navigator.app.backHistory();
}
}, false);
try
{
pushNotification = window.plugins.pushNotification;
$("#app-status-ul").append('<li>registering ' + device.platform + '</li>');
if (device.platform == 'android' || device.platform == 'Android' ||
device.platform == 'amazon-fireos' ) {
pushNotification.register(successHandler, errorHandler, {"senderID":"111111117746","ecb":"onNotification"}); // 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 APNS notifications for iOS
function onNotificationAPN(e) {
if (e.alert) {
$("#app-status-ul").append('<li>push-notification: ' + e.alert + '</li>');
// showing an alert also requires the org.apache.cordova.dialogs plugin
navigator.notification.alert(e.alert);
}
if (e.sound) {
// playing a sound also requires the org.apache.cordova.media plugin
var snd = new Media(e.sound);
snd.play();
}
if (e.badge) {
pushNotification.setApplicationIconBadgeNumber(successHandler, e.badge);
}
}
// handle GCM notifications for Android
function onNotification(e) {
$("#app-status-ul").append('<li>EVENT -> RECEIVED:' + e.event + '</li>');
switch( e.event )
{
case 'registered':
if ( e.regid.length > 0 )
{
$("#app-status-ul").append('<li>REGISTERED -> REGID:' + e.regid + "</li>");
// Your GCM push server needs to know the regID before it can push to this device
// here is where you might want to send it the regID for later use.
console.log("regID = " + e.regid);
}
break;
case 'message':
// if this flag is set, this notification happened while we were in the foreground.
// you might want to play a sound to get the user's attention, throw up a dialog, etc.
if (e.foreground)
{
$("#app-status-ul").append('<li>--INLINE NOTIFICATION--' + '</li>');
// on Android soundname is outside the payload.
// On Amazon FireOS all custom attributes are contained within payload
var soundfile = e.soundname || e.payload.sound;
// if the notification contains a soundname, play it.
// playing a sound also requires the org.apache.cordova.media plugin
var my_media = new Media("/android_asset/www/"+ soundfile);
my_media.play();
}
else
{ // otherwise we were launched because the user touched a notification in the notification tray.
if (e.coldstart)
$("#app-status-ul").append('<li>--COLDSTART NOTIFICATION--' + '</li>');
else
$("#app-status-ul").append('<li>--BACKGROUND NOTIFICATION--' + '</li>');
}
$("#app-status-ul").append('<li>MESSAGE -> MSG: ' + e.payload.message + '</li>');
//android only
$("#app-status-ul").append('<li>MESSAGE -> MSGCNT: ' + e.payload.msgcnt + '</li>');
//amazon-fireos only
$("#app-status-ul").append('<li>MESSAGE -> TIMESTAMP: ' + e.payload.timeStamp + '</li>');
break;
case 'error':
$("#app-status-ul").append('<li>ERROR -> MSG:' + e.msg + '</li>');
break;
default:
$("#app-status-ul").append('<li>EVENT -> Unknown, an event was received and we do not know what it is</li>');
break;
}
}
function tokenHandler (result) {
$("#app-status-ul").append('<li>token: '+ result +'</li>');
// Your iOS push server needs to know the token before it can push to this device
// here is where you might want to send it the token for later use.
}
function successHandler (result) {
$("#app-status-ul").append('<li>success:'+ result +'</li>');
}
function errorHandler (error) {
$("#app-status-ul").append('<li>error:'+ error +'</li>');
}
document.addEventListener('deviceready', onDeviceReady, true);
</script>
<div id="home">
<div id="app-status-div">
<ul id="app-status-ul">
<li>Cordova PushNotification Plugin Demo</li>
</ul>
</div>
</div>
</body>
</html>
Go to your plugins folder and check whether you have a folder named cordova-plugin-device.
That plugin should be installed in your project. So if that folder is missing you need to install it by opening your terminal and going to the root of your project to execute the following command
cordova plugin add cordova-plugin-device
This should add the plugin.
Found a solution for this myself. As it turned out, these two JS files:
<script type="text/javascript" charset="utf-8" src="cordova.js"></script>
<script type="text/javascript" src="PushNotification.js"></script>
had to been moved in HEAD section, not inside BODY section. Then it works fine!
Put your registration code under DeviceReady function
var platform = null;
document.addEventListener("deviceready", onDeviceReady, false);
function onDeviceReady() {
platform = device.platform;
//alert(platform);
$("#app-status-ul").append('<li>'+ platform +'</li>');
try
{
pushNotification = window.plugins.pushNotification;
$("#app-status-ul").append('<li>registering ' + device.platform + '</li>');
if (device.platform == 'android' || device.platform == 'Android' ||
device.platform == 'amazon-fireos' ) {
pushNotification.register(successHandler, errorHandler, {"senderID":"860557673192","ecb":"onNotification"}); // 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);
}
}

An error occured. Please try again later

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

Categories

Resources