How to call FB.api outside window.fbAsyncInit - facebook

so i have fb api initialized
window.fbAsyncInit = function() {
FB.init({
appId : '351808841561163',
status : true, // check login status
cookie : true, // enable cookies to allow the server to access the session
xfbml : true, // parse XFBML
oauth: true
});
and i have a separate js file with a function:
function example(){
FB.api(
'/me/[namespace]:visit',
'post',
{ channel: link},
function(response) {
if (!response || response.error) {
console.log(response.error);
} else {
console.log('Follow was success! Action ID: ' + response);
}
});
}
when i call this i get FB is undefined.
When i put the function inside window.fbAsyncInit it works ok , but i need to call the FB outside window.fbAsyncInit.
If there any possible way to do that?

just queue your function, and then call it right after FB initialized. Following code guarantees that your functions will be called in right order, and right after FB finish initialization
helper script you include BEFORE your example and before FB init script:
var FB; // to avoid error "undeclared variable", until FB got initialized
var myQueue = new Array();
function queueAdd(f){
if (FB == undefined)
myQueue.push(f);
else
f();
}
function processQueue(){
var f;
while(f = myQueue.shift())
f();
}
your function example:
function example(){
FB.api(
'/me/[namespace]:visit',
'post',
{ channel: link},
function(response) {
if (!response || response.error) {
console.log(response.error);
} else {
console.log('Follow was success! Action ID: ' + response);
}
});
}
queueAdd(example); // will run immediately if FB initialized. Otherwise, wait for FB first
and FB part:
window.fbAsyncInit = function() {
FB.init(blablabla);
processQueue();
}

Related

Facebook Login button failed to re-size in 45 seconds

I am attempting to implement an asynchronous loading Facebook log in button, but the button disappears after 45 seconds (in Google Chrome only) and this error message is logged in the error console: "FB:login_button failed to re-size in 45s". How do I solve this problem?
Here are the errors that are logged in the error console:
Uncaught TypeError: Cannot read property 'style' of undefined connect.facebook.net.js:123
v connect.facebook.net.js:123
o.extend.constructor.ha connect.facebook.net.js:123
g.inform connect.facebook.net.js:40
(anonymous function) connect.facebook.net.js:123
ka connect.facebook.net.js:67
h.setWrapper.j connect.facebook.net.js:62
r.register.init.s connect.facebook.net.js:66
h.setWrapper.j connect.facebook.net.js:62
fb:login_button failed to resize in 45s
Here is the HTML:
<div class="fb-login-button" data-show-faces="false" size="xlarge" data-width="300" data-max-rows="1"></div>
Here is the Javascript:
ADS.addEvent(window, "load", function(){
if(!ADS.$('fb_root')){
var div = document.createElement('div');
div.id = "fb-root";
document.body.appendChild(div);
var script = document.createElement("script");
script.src = "dom/connect.facebook.net.js";
var script2 = document.createElement("script");
var head = document.getElementsByTagName("head")[0];
head.appendChild(script);
window.fbAsyncInit = function () {
FB.init({
appId: "HIDDEN",
channelUrl: "http://mywebsite.com/channel.php",
status: true,
cookie: true,
xfbml: true
});
// Gets status when the user first lands
// on site
FB.getLoginStatus(function(response) {
if (response.status === 'connected') {
//window.location="http://mywebsite.com";
} else if (response.status === 'not_authorized') {
// Do nothing, let the user view the welcome page
//FB.login();
} else {
// this causes a login dialog to
// pop up automagically once the user
// lands on the site and is not logged in
// or authorized
//FB.login();
}
});
function login() {
FB.login(function(response) {
if (response.authResponse) {
// connected
// using event subscribe to send user to right page, instead of this
// which does not redirect the user once the login is complete
//window.location="http://mywebsite.com/home.php?show=follow";
} else {
// cancelled
//alert(response.authResponse);
}
});
}
FB.Event.subscribe("auth.login", function () {
// Redirect's the user once the login is complete
window.location="http://mywebsite.com";
})
}
}
});

how to use backbone.js and implement FB.Event.subscribe

I am using backbone.js to implement a login page with a facebook login button.
window.LoginPage = Backbone.View.extend({
initialize:function () {
this.template = _.template(tpl.get('login-page'));
},
render:function (eventName) {
$(this.el).html(this.template(this.model.toJSON()));
this.bind("nav", this.nav,this);
this.model.bind("reset", this.render, this);
return this;
},
events:{
"click #login":"login"
},
login:function(){
FB.login(
function(response) {
if (response.authResponse) {
console.log('Welcome! Fetching your information.... ');
FB.api('/me', function(response) {
console.log('Good to see you, ' + response.name + '.');
}
);
} else {
console.log('User cancelled login or did not fully authorize.');
}
},
{ scope: "email" }
);
}
});
This works, I can login with my facebook app. But after the login I want the FB.event.subscribe to be triggered. But I do not have a clue how to implement this with backbone.js
FB.Event.subscribe('auth.login', function(response) {
Backbone.history.navigate("#locallist",true)
});
Not sure what you mean with "I want the FB.event.subscribe to be triggered". If you have the FB object on your window, you can just start binding events wherever.
I think your problem will be that you can't guarantee when or if the FB object is on the window, so something that I have in my applications is to create a global event and make my app listen to that event. Here's some pseudo-code in CoffeeScript:
class FacebookServiceProvider extends ServiceProvider
constructor: ->
super
initialize: (options) ->
FB.init
appId: appId,
status: true,
cookie: true,
xfbml: true,
oauth: true
app.trigger 'facebook:initialized'
window.facebookInitialized = true
#
class FacebookView extends Backbone.View
initialize: (options) ->
if window.facebookInitialized
onFacebookInitialized.call #
app.on 'facebook:initialized', #onFacebookInitialized, #
#
onFacebookInitialized: =>
FB.Event.subscribe 'auth.authResponseChange', (response) -> console.log response
#
basically just using a global variable on the window to see whether the facebook service provider has been initialized and if so, depending on the state, my view will render or listen to FB events only when it can and no sooner.

Check if Facebook JS-API app already has been given permission

I have a small script that unlocks some content on a page when a user logs in via Facebook and posts some information on their wall.
I want to avoid any duplicate posts (spam) in the event the user visits the page a second time and repeats the process.
Is there a way of (when asking for the permissions) to tell if they have already been given and therefore skip the sharing part of the script?
Here's my code:
$('.preview a').click(function(e) {
e.preventDefault();
FB.login(function(response) {
if (response.session) {
FB.api('/me/feed', 'post', {
message: 'Just unlocked the exclusive preview of...',
picture: 'http://website.com/share.png',
link: 'http://www.website.com',
name: 'Name goes here',
description: 'Description here'
},
function(response) {
if (!response || response.error) {
alert(response.error);
} else {
$('.preview').hide();
$('.clip').show();
}
});
}
},
{perms:'read_stream,publish_stream'});
});
From 2011 to 2014 a lot of things change..
I made this solution to check for "user_friends" and "publish_actions" permissions, if not allowed the both, force the user to "re-autenticate". The callback method will only be called when all permissions are given.
function login(cb,forceAuth) {
FB.getLoginStatus(function (response) {
if (response.status !== 'connected' || forceAuth==true){
FB.login(function (response) {
checkPermissions(cb,false);
}, {scope: 'publish_actions,user_friends'});
} else {
checkPermissions(cb);
}
});
}
function checkPermissions(cb,forceAuth){
FB.api(
"/me/permissions",
function (response) {
if (response.data[0]['publish_actions']==undefined || response.data[0]['publish_actions']==0 ||
response.data[0]['user_friends']==undefined || response.data[0]['user_friends']==0) {
if (forceAuth!=false)
login(cb,true);
} else {
cb();
}
}
);
}
How to use:
login(function () {
myLogedAndAllowedFunction();
});
I've written a tutorial about this here, and here's an example:
FB.api({ method: 'fql.query', query: 'SELECT read_stream,offline_access,publish_stream FROM permissions WHERE uid=me()' }, function(resp) {
for(var key in resp[0]) {
if(resp[0][key] === "1")
console.log(key+' is granted')
else
console.log(key+' is not granted')
}
});
There's also a JS REST example there in the article just for reference.

Facebook Connect does not process jQuery ajax call after successful login

I've got the following script:
<script>
window.fbAsyncInit = function () {
FB.init({ appId: '<%: Facebook.FacebookApplication.Current.AppId %>',
status: true,
cookie: true,
xfbml: true,
oauth: true
});
function FBLogin() {
FB.login(function (response) {
if (response.authResponse) {
ConnectFacebookUser(response.authResponse.accessToken);
} else {
alert('User cancelled login or did not fully authorize.');
}
}, { scope: 'email' });
}
$('#fb-button').live('click', function (e) {
FBLogin();
e.preventDefault();
});
function ConnectFacebookUser(at) {
var postdata = "at=" + at;
alert('This is the access token : ' + at);
$.ajax({
type: "POST",
dataType: "json", // what data type to expect from the server
url: "/FBConnect.ashx",
data: postdata,
success: function (data) {
// do nothing
alert('all good');
},
error: function (xhr, status, error) {
alert('error occured in FBConnect.ashx');
}
});
alert('finished');
}
};
(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>
And for the html fragment:
Login with facebook
<div id="fb-root"></div>
When the link is clicked, a popup window for facebook shows up and when i enter my login details, i only see an alert to say "This is the access token..." but the rest of the code don't get processed. If I click the "login with facebook" link one more time, then everything gets processed as normal.
What could be the problem?
It works for me. I get the message 'this is the acccess code' and then i get a 'finished' alert. Check your Chrome debugger tools to look for any script errors that may be occuring silently.
Check out https://github.com/xocialhost/jquery.xocialCore.js/blob/master/jquery.xocialCore.js to see a jQuery specific way of doing this. One thing I noticed is that the jQuery click function when calling the FB.login was triggering the popup blocker in a few browsers I was testing with. I set this up to work around that issue but it's also a way to add a callback that is run properly during the init sequence.

Publish to Current user's wall using FBJS in FBML application

I need to publish some message to the current user's wall using FBJS in FBML application.
When I use
window.fbAsyncInit = function() {
FB.init({appId: 'MY_APP_ID', status: true, cookie: true, xfbml: false});
};
i am getting an error :- FB is not defined.
and
window is not defined.
For publishing i am using this code
function graphStreamPublish(){
var body = document.getElementById("txtTextToPublish").value;
FB.api('/me/feed', 'post', { message: body }, function(response) {
if (!response || response.error) {
// alert('Error occured');
} else {
// alert('Post ID: ' + response.id);
}
});
}
(I cannot use alert in facebook..)
Thanks in advance..
If you're using FBML, you should be using FBJS instead of the Facebook Connect API.
var body = document.getElementById('txtTextToPublish').getValue();
Facebook.streamPublish(body);
Note the getValue() call instead of .value due to use of FBJS.