Cordova Facebook login - facebook

I installed the plugin as mentioned in the docs
I cant find a way to get it working.
When I run the apk on android I get this:
Uncaught ReferenceError: facebookConnectPlugin is not defined(…)
Here are me files.
index.html
<body>
<div class="app">
<div id="fb-root"></div>
<h1>Apache Cordova</h1>
<div id="deviceready" class="blink">
<p class="event listening">Connecting to Device</p>
<p class="event received">Device is Ready</p>
</div>
</div>
<script type="text/javascript" src="cordova.js"></script>
<script type="text/javascript" src="js/index.js"></script>
</body>
<div id="fb-root"></div>
index.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 explicitly call 'app.receivedEvent(...);'
onDeviceReady: function() {
app.receivedEvent('deviceready');
},
// 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);
//FB login
facebookConnectPlugin.login(
["public_profile"],
fbLoginSuccess,
function (error) { alert("" + error) }
);
var fbLoginSuccess = function (userData) {
alert("UserInfo: " + JSON.stringify(userData));
}
}
};
app.initialize();

I've had issues with using the FB plugin in my app development too. Sometimes it's necessary to include the FacebookConnectPlugin.js file in your index.html, as well as include this script, which injects the Facebook Javascript SDK into your app.
Source: https://github.com/driftyco/ng-cordova/issues/446
Other threads about the same issue:
Cordova/Phonegap-facebook-plugin Android: facebookConnectPlugin is not defined
facebookConnectPlugin is not defined
facebookConnectPlugin is not defined (ngCordova, Ionic app)
...

Related

Facebook Login Button not appearing in ui-view child

I'm making an AngularJS app with the facebook sdk. The structure comes as follows:
<html xmlns:fb="http://ogp.me/ns/fb#">
<head>
<title>Reportes para Anunciantes</title>
<meta charset="UTF-8">
<script type="text/javascript" src="js/angular.min.js"></script>
<script type="text/javascript" src="js/angular-ui-router.min.js"></script>
<!-- more scripts here -->
<script type="text/javascript" src="js/index.js"></script>
</head>
<body>
<script type="text/javascript">
window.fbAsyncInit = function() {
FB.init({
appId : 'MYAPPID', //Have an actual app id in my source
cookie : true, // enable cookies to allow the server to access
// the session
xfbml : true, // parse social plugins on this page
version : 'v2.0' // use version 2.0
});
angular.bootstrap(document, ['Application']);
};
// Load the SDK asynchronously
(function(d, s, id) {
var js, fjs = d.getElementsByTagName(s)[0];
if (d.getElementById(id)) return;
js = d.createElement(s); js.id = id;
js.src = "//connect.facebook.net/es_LA/sdk.js";
fjs.parentNode.insertBefore(js, fjs);
}(document, 'script', 'facebook-jssdk'));
</script>
<div id="content" ui-view>
Cargando API de Facebook ...
</div>
</body>
</html>
In the page, I load Angular once the Facebook API is loaded. The site uses xfbml for the login buttons.
The whole angular app is in index.js:
var Application = angular.module(
"Application",
['ui.router'],
['$stateProvider', function($stateProvider){
//$httpProvider.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded;charset=utf-8';
$stateProvider
.state('notloggedin', {
templateUrl: 'templates/notloggedin.html',
controller: 'Application.NotLoggedIn'
})
.state('notauthorized', {
templateUrl: 'templates/notauthorized.html',
controller: 'Application.NotAuthorized'
})
.state('inapp', {
templateUrl: 'templates/inapp.html',
controller: 'Application.InApp'
});
}]
);
function FBStatusChecker($state){
this._state = $state;
}
FBStatusChecker.prototype = {
checkAndGo: function(response) { /* omitted - no issue here */ },
/* omitted methods - no issue here */
updateState: function(){
var context = this;
FB.getLoginStatus(function(response) {
context.checkAndGo(response);
})
}
};
Application.StatusChangeService = Application.service('Application.FBStatusChecker', ['$state', FBStatusChecker]);
Application.directive("fbLoginButton", function() {
return {
restrict: 'E',
link: function (scope, iElement, iAttrs) {
console.log("your ass");
if (FB) {
console.log("is broken");
FB.XFBML.parse(iElement[0]);
}
}
}
});
/* omitted controllers - no issue here.
two of them are empty, and one correctly updates the scope
via $scope.$apply(...) for an asynchronous callback */
Application.run(['Application.FBStatusChecker', function(statusChecker){
statusChecker.updateState();
}]);
Let's analyze by parts:
The page uses ui-router to switch between application states. This works as expected. Angular is only loaded (i.e. my module being run) once the FB API was successfully loaded.
The application defines three states, and in run() one of those states is selected.
I omitted the controllers, since two are empty, and the third updates -with no issues- the scope.
I omitted the state-switcher service methods (this has the task to use $state to switch to one of three states depending on facebook state).
There's a directive named fbLoginButton. This directive must be recognized as 'E' (lement), and should match fb:login-button. The directive is successfully matched.
I had no issue generating the button before using AngularJS and ui-router.
Finally, the templates come:
notloggedin.html
<fb:login-button max_rows="1" size="xlarge" show_faces="false" auto_logout_link="false"></fb:login-button>
Debes iniciar sesión en Facebook para continuar.
notauthorized.html
<fb:login-button max_rows="1" size="xlarge" show_faces="false" auto_logout_link="false"></fb:login-button>
Debes autorizar la aplicación para continuar.
inapp.html
<span ng-if="name">
Bienvenido {{ name }}!
</span>
<span ng-if="!name">
Listando ...
</span>
Notes: Also tried HTML5 solution, using div, instead of xfbml.
And my issue is: The facebook buttons are not being shown. Only the corresponding texts are being shown. If i'm logged in Facebook when I hit this page, I get correctly redirected to the expected state, with the {{ name }} being fetched. The same occurs with the other states, so I'm not having issue specificly with graph api, but with xfbml.
And my question is: What am I missing? The directive is being matched but seems that FM.XML.parse has no effect. How can I fix it?
Apparently -discovered it by a lucky mistake- the .parse method ignores the current element, so the parse must start from the parent element. So far, the directive must be changed to:
Application.directive("fbLoginButton", function() {
return {
restrict: 'E',
link: function (scope, iElement, iAttrs) {
if (FB) {
FB.XFBML.parse(iElement[0].parent);
}
}
}
});
which consisted in just adding the .parent property to get the parent DOM node.
However, if two items matched by this directive are siblings (or using another directive with the same functionality), this could be run twice. So recording the element in an array after parsing it, and checking before parsing it, would be a good workaround to avoid doing the parsing twice. Another alternative would be to force a parsing in each state's controller, to the ui-view-holding container. The latter would be implemented like this:
The only directive will be an attribute-based directive, e.g. xfbml-parse in the ui-view element (in my case):
Application.directive("fbLoginButton", function() {
return {
restrict: 'E',
link: function (scope, iElement, iAttrs) {
if (FB) {
FB.XFBML.parse(iElement[0].parent);
}
}
}
});
being no need to implement other directives.
After that, use xfbml-parse directive in the ui-view element. In my case:
<div id="content" ui-view xfbml-parse>
Cargando API de Facebook ...
</div>
which will run the link function every time the state changes.
So: every time the ui-view node renders, the XFBML will be parsed.

Post on Facebook wall with Javascript sdk

So, I'm trying to post on users wall using fb.api and I'm stuck.
Here is my code:
<html xmlns="http://www.w3.org/1999/xhtml" xmlns:fb="http://www.facebook.com/2008/fbml"><head><meta http- equiv="Content-Type" content="text/html; charset=windows-1251">
<title>Example Of Posting To Wall Using Javascript Graph API</title>
<script type="text/javascript" src=""></script>
</head>
<body class="">
//the facebook sdk include
<div id="fb-root" class=" fb_reset">
<script>
var APP_ID="myAppID";
window.fbAsyncInit = initFacebook;
function initFacebook()
{
FB.init({
appId : APP_ID,
status : true, // check login status
cookie : false, // enable cookies to allow the server to access the session
xfbml : true // parse XFBML
});
FB.getLoginStatus(onFacebookLoginStatus);
};
(function() {
var e = document.createElement('script');
e.src = document.location.protocol + '//connect.facebook.net/en_US/all.js';
e.async = true;
document.getElementById('fb-root').appendChild(e);
}());
//the login function
function facebookLogin()
{
var loginUrl="http://www.facebook.com/dialog/oauth/?"+
"scope=publish_stream&"+
"client_id="+APP_ID+"&"+
"redirect_uri="+document.location.href+"&"+
"response_type=token";
window.location=loginUrl;
}
//Callback function for FB.login
function onFacebookLoginStatus(response)
{
if (response.status=="connected" && response.authResponse)
{
document.getElementById("txtEcho").innerHTML="Logged in.";
}
else
{
document.getElementById("txtEcho").innerHTML="Not logged in.";
}
}
//post to wall function
function postToWallUsingFBApi()
{
var data=
{
caption: 'This is my wall post example',
message: 'Posted using FB.api',
link: 'http://wwww.permadi.com/blog/',
}
FB.api('/me/feed', 'post', data, onPostToWallCompleted);
}
//the return function after posting to wall
function onPostToWallCompleted(response)
{
if (response)
{
if (response.error)
{
document.getElementById("txtEcho").innerHTML=response.error.message;
}
else
{
if (response.id)
document.getElementById("txtEcho").innerHTML="Posted as post_id "+response.id;
else if (response.post_id)
document.getElementById("txtEcho").innerHTML="Posted as post_id "+response.post_id;
else
document.getElementById("txtEcho").innerHTML="Unknown Error";
}
}
}
</script>
<input id="loginButton" type="button" value="Login To Facebook" onclick="javascript:facebookLogin();">
<input id="postToWallWithFBApiPrompt" type="button" value="Post To Wall Using FB.api" onclick="javascript:postToWallUsingFBApi();">
<div id="txtEcho"><b></b></div>
</body>
</html>
The problem here is that I receive this error code: An active access token must be used to query information about the current user.
I get that even if I use the log in button to get the code. Is there a possibility to add previously obtained access token in function postToWallUsingFBApi(). And can I change the /me/ with user id, so that way the user can be logged out and still post?
If you are doing client-side login that way, you have to extract the access token from the URL yourself afterwards – see https://developers.facebook.com/docs/howtos/login/client-side-without-js-sdk/#step3
Or you just use the FB.login method out of the JS SDK – a little easier, handles all the ecessary stuff “out of the box” – https://developers.facebook.com/docs/howtos/login/getting-started/#step4

Looking for working example of WP7 PhoneGap Facebook plugin for signin button

I've tried all the code at https://github.com/davejohnson/phonegap-plugin-facebook-connect
that is recommended by the phonegap community, but i keep running into errors trying to get it to work.
As you can see I'm using cordova 1.6.0 which maybe the problem?
i've added the script files to in my html page
<script type="text/javascript" charset="utf-8" src="cordova-1.6.0.js"></script>
<script type="text/javascript" charset="utf-8" src="cdv-plugin-fb-connect.js">/script>
<script type="text/javascript" charset="utf-8" src="facebook_js_sdk.js"></script>
<script type="text/javascript" charset="utf-8" src="ChildBrowser.js"></script>
And I've added the ChildBrowserCommand.cs into the plugins directory.
I then added this to device ready listener with my authentic app id (the real id not shown here)
document.addEventListener("deviceready",onDeviceReady,false);
// once the device ready event fires, you can safely do your thing! -jm
function onDeviceReady() {
//document.getElementById("welcomeMsg").innerHTML += "Cordova is ready! version=" + window.device.cordova;
console.log("onDeviceReady. You should see this message in Visual Studio's output window.");
//fb connect sign in
try {
//alert('Device is ready! Make sure you set your app_id below this alert.');
console.log('Device is ready! Make sure you set your app_id below this alert.');
FB.Cookie.setEnabled(true); // this seems to be duplicate to 'cookie: true' below, but it is IMPORTANT due to FB implementation logic.
FB.init({ appId: "311961255484993", nativeInterface: CDV.FB, cookie: true });
login();
} catch (e) {
//alert(e);
console.log("Init error: " + e);
}
};
function login() {
FB.login(
function (response) {
if (response.session) {
console.log('logged in');
} else {
console.log('not logged in');
}
},
{ scope: 'email, read_stream, read_friendlists' }
);
}
The error i get is
Unable to locate command :: org.apache.cordova.facebook.Connect
Any help?
EDIT: I also realize it's coming from cdv-plugin-fb-connect.js in here but not sure why?
cordova.exec(function () {
var authResponse = JSON.parse(localStorage.getItem('cdv_fb_session') || '{"expiresIn":0}');
if (authResponse && authResponse.expirationTime) {
var nowTime = (new Date()).getTime();
if (authResponse.expirationTime > nowTime) {
// Update expires in information
updatedExpiresIn = Math.floor((authResponse.expirationTime - nowTime) / 1000);
authResponse.expiresIn = updatedExpiresIn;
localStorage.setItem('cdv_fb_session', JSON.stringify(authResponse));
FB.Auth.setAuthResponse(authResponse, 'connected');
}
}
console.log('Cordova Facebook Connect plugin initialized successfully.');
}, (fail ? fail : null), 'org.apache.cordova.facebook.Connect', 'init', [apiKey]);
},

Facebook FB.Event.subscribe "bug" with the edge.create callback

Im fancing a really weird problem with the edge.create callback.
What im doing is to execute an ajax call to the server each time an edge.create or edge.remove event occurs (the firs is to like and the second to unlike a page).
Heres the code
// this will fire when any of the like widgets are "liked" by the user
FB.Event.subscribe('edge.create', function(href, widget) {
var dataSend = 'ajaxFace=true&submitAdd=true&code='+SomeCodeToAdd;
$.ajax({
type: 'POST',
url: 'http://somewebpage.com',
data: dataSend,
success: function(data) {
alert(data);
},
erro: function(data) {
alert('Try again later');
}
});
});
//this will fire when any widgets are "disliked" by the user
FB.Event.subscribe('edge.remove', function(href, widget){
var dataSend = 'ajaxFace=true&submitDelete=true&code='+SomeCodeToRemove;
$.ajax({
type: 'POST',
url: 'http://somewebpage.com',
data: dataSend,
success: function(data) {
alert(data);
},
erro: function(data) {
alert('Try again later');
}
});
});
Now, whats happening.
The function for the 'edge.remove' event works smooth and without any problems.
But when the user click like the code simply dont run on the success part of the ajax call, i tryed a simple alert like alert('test'); but nothing happens too. The code, however, works fine on the backend and the code I want to add is added with success.
However if i set the async : false the code works, the alerts is presented on the page but the browser gets that nasty "lock down" that i really want to avoid.
So, anyone have any idea whats exactly going on here?
PS.: Theres 2 others facebook elements on this page, the comments and activity feed. I dont know but im with the impression that the activity feed may have something to do with this...
I think this is some sort of scope issue. If you define the function containing the ajax call outside of the scope of the FB.Event.subscribe, and just call that function from within the FB.Event.subscribe, that may fix the issue.
HI i was facing the same problem but for different FB event. Here is my code an it 100% working :-
<!doctype html>
<html lang="en" xmlns:fb="https://www.facebook.com/2008/fbml">
<head>
<meta charset="utf-8">
<title>Facebook Like Button</title>
<script src="http://code.jquery.com/jquery-1.9.1.min.js"></script>--->(DO not forget to include)
</head>
<body>
<div id="fb-root"></div>
<script>
window.fbAsyncInit = function() {
FB.init({appId: '464134126954048', status: true, cookie: true,xfbml: true});
FB.Event.subscribe("message.send", function(targetUrl) {
$.ajax({
url:'abc.php',
type:'POST',
data:{name:'sunlove'},
success:function(data)
{
alert("I am here");
}
});
});
};
(function() {
var e = document.createElement('script'); e.async = true;
e.src = document.location.protocol +
'//connect.facebook.net/en_US/all.js';
document.getElementById('fb-root').appendChild(e);
}());
</script>
<fb:send href="http://demo.antiersolutions.com/studybooster1.2"></fb:send>
<script type="text/javascript" src="http://platform.twitter.com/widgets.js"> </script>
</body>
</html>
You can just copy and make new file and customize according to your need

how to get user facebook logged in status

i am working on a small application in asp.net, c# in my website, which shows user is logged into facebook in the same browser. Which means in the browser if user open my website(in same browser if user is not logged into facebook) a popup should show that user is not loggedin. if the user logged into facebook then a popup should come in my website showing that loggedin after refresh of my page.
in a page refresh i just want to alert the login status of user...
i had the xd_receiver.htm file in my root directory and
this script in header and
Untitled Page
<script src="http://static.ak.connect.facebook.com/js/api_lib/v0.4/FeatureLoader.js.php"
type="text/javascript"></script>
<script type="text/javascript" src="http://connect.facebook.net/en_US/all.js#appId=142899075774321&xfbml=1"></script>
<script type='text/javascript' language='javascript'>
window.onload = function() {
FB.init('142899075774321', 'xd_receiver.htm');
alert("Before ensureInit");
FB.ensureInit(function() {
alert("After ensureInit");
FB.Connect.ifUserConnected(onUserConnected, onUserNotConnected);
});
};
function onUserConnected() {
alert('connected!');
window.location.reload();
}
function onUserNotConnected() {
alert('not connected');
}
</script>
this script in body....
But this code is not working.....
how should i solve this......
thanks in advance
Try this for the html head part:
<title>Facebook Status</title>
<script src="http://static.ak.connect.facebook.com/js/api_lib/v0.4/FeatureLoader.js.php/en_US"
type="text/javascript">
</script>
<script type="text/javascript">
var api_key = 'Your app id';
var channel_path = 'xd_receiver.htm';
//alert(document.referrer);
FB_RequireFeatures(["XFBML"], function() {
// Create an ApiClient object, passing app's API key and
// a site relative URL to xd_receiver.htm
FB.Facebook.init(api_key, channel_path);
FB.Connect.get_status().waitUntilReady(function(status) {
switch(status) {
case FB.ConnectState.connected:
document.getElementById("divstatus").innerHTML ="LOGGED IN AUTHORIZED";
break;
case FB.ConnectState.appNotAuthorized:
document.getElementById("divstatus").innerHTML ="LOGGED IN NOT AUTHORIZED";
break;
case FB.ConnectState.userNotLoggedIn:
document.getElementById("divstatus").innerHTML ="NOT LOGGED IN";
break;
}
});
});
</script>
Then use this for the html > body part:
<div id="divstatus">
</div>