Google Chrome can't run script in FB javascript SDK? - javascript

I have a sample code:
<script>
window.fbAsyncInit = function() {
// init the FB JS SDK
FB.init({
appId : 'xxx', // App ID from the App Dashboard
status : true, // check the login status upon init?
cookie : true, // set sessions cookies to allow your server to access the session?
xfbml : true // parse XFBML tags on this page?
});
FB.getLoginStatus(function(response) {
var page_id = "40796308305"; // cocacola
if (response && response.authResponse) {
var user_id = response.authResponse.userID;
var fql_query = "SELECT uid FROM page_fan WHERE page_id = "+page_id+"and uid="+user_id;
FB.Data.query(fql_query).wait(function(rows) {
if (rows.length == 1 && rows[0].uid == user_id) {
$('#fbframe').css('display', 'none');
} else {
$('#fbframe').css('display', 'block');
}
});
} else {
alert("Login to like");
}
});
}
(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/en_US/all.js#xfbml=1";
fjs.parentNode.insertBefore(js, fjs);
}(document, 'script', 'facebook-jssdk'));
And html
<div id="fbframe">
<fb:like href="https://www.facebook.com/coca-cola" send="false" width="450" show_faces="false"></fb:like>
</div>
When I run code, has liked page facebook.com/coca-cola, but $('#fbframe').css('display', 'none'); not run in chrome(firefox run OK)

My guess is that the jQuery library hasn't yet loaded when you first call it.
If you are going to be using jQuery, you need to make sure the document has loaded first.
Wrap you loginStatus call like this:
$(document).ready(function() {
FB.getLoginStatus(function(response) {
var page_id = "40796308305"; // cocacola
if (response && response.authResponse) {
var user_id = response.authResponse.userID;
var fql_query = "SELECT uid FROM page_fan WHERE page_id = "+page_id+"and uid="+user_id;
FB.Data.query(fql_query).wait(function(rows) {
if (rows.length == 1 && rows[0].uid == user_id) {
$('#fbframe').css('display', 'none');
} else {
$('#fbframe').css('display', 'block');
}
});
} else {
alert("Login to like");
}
});
});

Related

Facebook Login JS SDK - getLoginStatus always return unknown

Always when I try to log in with Facebook, using the JavaScript SDK, and want to get the log in status I receive a response with 'unknown'. I read all Facebook's documentation and a lot post and I still having the same error.
I'm using Google Chrome VersiĆ³n 61.
This is my code:
(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.com/en_US/sdk.js";
fjs.parentNode.insertBefore(js, fjs);
}(document, 'script', 'facebook-jssdk'));
window.fbAsyncInit = function() {
FB.init({
appId : appID,
xfbml : true, // parse XFBML
status : true, // check login status
cookie : true, // enable cookies to allow the server to access the session
version : 'v2.10'
});
FB.AppEvents.logPageView();
// Get current login url
var url = new URL(window.location.href);
// Get if the user has been connected via Facebook
var conn = url.searchParams.get("connected");
// Check the var
if(conn == "true" || conn == true){
loginWithFacebook(null);
}
};
// Login with Facebook
function loginWithFacebook(elementButton){
// Javascript URL
var strUri = encodeURI('https://vinglet.com/login?connected=true'),
myPermissionLogIN = 'email,public_profile';
// Check if the user has initialized session on the app
FB.getLoginStatus(function(response) {
// Check the status of the user
if (response.status !== 'connected'){
window.location.href = 'https://graph.facebook.com/oauth/authorize?client_id='+appID+'&scope='+myPermissionLogIN+'&redirect_uri='+strUri;
}
else{
var meObject = {
fields: `first_name, last_name, email, public_key,
middle_name, link, gender, birthday, about`
};
// Save the data into the DB
loginWithFacebookAJAX(meObject,elementButton);
}
});
}

Get facebook friends list in js using graph API

I have created an app on Facebook. I want to refer that app to a friend so for that I want to display the list of friends. I'm getting only user info but not the friend list.
I have used the below code, please help me get the friend list.
window.fbAsyncInit = function() {
FB.init({
appId : 'xxxxxxxxxxxxxxxxxxx',
xfbml : true,
version : 'v2.4'
});
function onLogin(response) {
if (response.status == 'connected') {
FB.api('/me?fields=first_name', function(data) {
var welcomeBlock = document.getElementById('fb-welcome');
welcomeBlock.innerHTML = 'Hello, ' + data.first_name + '!';
});
}
}
FB.getLoginStatus(function(response) {
// Check login status on load, and if the user is
// already logged in, go directly to the welcome message.
if (response.status == 'connected') {
onLogin(response);
} else {
// Otherwise, show Login dialog first.
FB.login(function(response) {
onLogin(response);
}, {scope: 'user_friends, email'});
}
});
};
(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/en_US/sdk.js";
fjs.parentNode.insertBefore(js, fjs);
}(document, 'script', 'facebook-jssdk'));
function getFriends() {
alert("in friends");
FB.api('/me/friends', 'GET',{},
function(response) {
if (response.data) {
console.log(response.data);
$.each(response.data,function(index,friend) {
console.log(friend.name +'has id:'+friend.id);
// alert(friend.name);
});
} else {
alert("Error!");
}
});
}
You don't even request the friends in your code. Since Graph API v2.0, you'll only receive the friends which are also using your app, and not all friends.
Use
FB.api('/me?fields=first_name,friends', function(data) { ... });
In App Friends
FB.api("/me/friends",function(res) {
console.log(res)
});
doc
Inviable Friends(only in Game)
FB.api("/me/invitable_friends",function(res){
console.log(res)
});
doc

Need a workaround to stop Safari browser blocking Facebook authentication pop up box for allowing users to login to my site

I've set up the Parse/Facebook login workflow (JavaScript SDK) for my site as seen here https://parse.com/docs/js/guide#users-facebook-users This works on desktop , but on mobile devices because of the Fb authentication using a pop up box in the workflow, I'm unable to make this work (Unless I adjust my browser settings manually, which isn't of course isn't an option for other users)
I've researched it, but can't seem to find a solution I've been able to implement. Has any one been able to solve this?
I've followed the guidance seen in the following places:
Facebook Login not open in Safari/ iPhone
Prevent pop-ups from being blocked
Error/blank page with Chrome and Safar browser apps for iphone when using javascript FB login code
My current code for this is
Function FBLogin() {
//Fb app information//
window.fbAsyncInit = function() {
Parse.FacebookUtils.init({
appId : 'XXXXX',
xfbml : true,
version : 'v2.3'
});
//FB user authentication script//
var uri = encodeURI('http://XXXXX/user_home.html');
Parse.FacebookUtils.logIn(null, {
success: function(user) {
if (!user.existed()) {
window.location.href=uri;
} else {
window.location = encodeURI("https://www.facebook.com/dialog/oauth?client_id=XXXXXXXXX&redirect_uri="+uri+"&response_type=token");
}
},
error: function(user, error) {
}
});
};
(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/en_US/all.js";
fjs.parentNode.insertBefore(js, fjs);
}(document, 'script', 'facebook-jssdk'));
}
I found the answer on this site for a pure FB JS SDK link, my code below is adjusted to make it work for Parse.
function getUserData() {
FB.api('/me', function(response) {
document.getElementById('response').innerHTML = 'Hello ' + response.name;
});
}
window.fbAsyncInit = function() {
//SDK loaded, initialize it
Parse.FacebookUtils.init({
appId : 'XXXXXX',
xfbml : true,
version : 'v2.2'
});
//check user session and refresh it
var uri = encodeURI('http://XXXXX/XXXXXX.html');
FB.getLoginStatus(function(response) {
if (response.status === 'connected') {
//user is authorized
document.getElementById('loginBtn').style.display = 'none';
getUserData();
} else {
//user is not authorized
}
});
};
//load the JavaScript SDK
(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/en_US/all.js";
fjs.parentNode.insertBefore(js, fjs);
}(document, 'script', 'facebook-jssdk'));
//add event listener to login button
document.getElementById('loginBtn').addEventListener('click', function() {
//do the login
var uri = encodeURI('http://XXXXX/XXXXX.html');
Parse.FacebookUtils.logIn(null, {
success: function(user) {
if (!user.existed()) {
window.location.href=uri;
} else {
window.location = encodeURI("https://www.facebook.com/dialog/oauth?client_id=ADDYOURAPPIDHERE&redirect_uri="+uri+"&response_type=token");
}
},
error: function(user, error) {
}
});
}, false);

javascript - show if user logged to facebook

I want to check if a user is logged in facebook (not necessarily from my site).
when i debug my script i see that it fails to execute FB.getLoginStatus().
I also tried other FB functions, but it seems it doesn't recognize any of them except for FB.init. why do they fail? any help would be appreciated
<div id="fb-root"></div>
<script type="text/javascript" src="//connect.facebook.net/en_US/all.js">
</script>
<script type="text/javascript">
window.fbAsyncInit = function() {
FB.init({
appId : 'my_app_id', // App ID
status : true, // check login status
cookie : true, // 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'; if (d.getElementById(id)) {return;}
js = d.createElement('script'); js.id = id; js.async = true;
js.src = "//connect.facebook.net/en_US/all.js";
d.getElementsByTagName('head')[0].appendChild(js);
}(document));
function GetFBLoginStatus() {
debugger;
window.fbAsyncInit()
alert("get status");
FB.getLoginStatus(function(response) {
alert("inside call back function");
if (response.status === 'connected') {
// var uid = response.authResponse.userID;
// var accessToken = response.authResponse.accessToken;
// alert("Connected FBID = " + uid);
} else if (response.status === 'not_authorized') {
alert("not_authorized");
} else {
alert("Not Logged into facebook");
}
return true;
}, true)
}
</script>
EDIT
You seems to have omitted something important in your code, please, try with this, it works for me:
window.fbAsyncInit = function() {
FB.init({
appId : '', // App ID
status : true, // check login status
cookie : true, // enable cookies to allow the server to access the session
xfbml : true // parse XFBML
});
// Here we subscribe to the auth.authResponseChange JavaScript event
FB.Event.subscribe('auth.authResponseChange', function(response) {
// Here we specify what we do with the response anytime this event occurs.
if (response.status === 'connected') {
// logged into the app
alert('logged');
} else if (response.status === 'not_authorized') {
// In this case, the person is logged into Facebook, but not into the app
alert('not authorized but logged into fb')
} else {
// not logged into Facebook
alert('not logged');
}
});
};
// 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));
Last thing: pay attentions to "duplicate questions" in few hours
END EDIT
That's your code?
This 'my_app_id'
appId : 'my_app_id', // App ID
it's a value that fb will generate when you will create an app, you need this number before everything.
If you aren't a web developer (needed to create an app), you can go here, after you join the developer team, you can create an app and get your app id. Enough clear?

Facebook JS SDK returns no results

I ran an example copied from:
http://developers.facebook.com/docs/reference/javascript/
http://developers.facebook.com/docs/reference/javascript/FB.api/
(I only changed my APP_ID)
<div id="fb-root"></div>
<script>
window.fbAsyncInit = function() {
FB.init({
appId : 'MY_ID', // App ID
channelUrl : '//WWW.YOUR_DOMAIN.COM/channel.html', // Channel File
status : true, // check login status
cookie : true, // enable cookies to allow the server to access the session
xfbml : true // parse XFBML
});
FB.api('/platform/posts', { limit: 3 }, function(response) {
for (var i=0, l=response.length; i<l; i++) {
var post = response[i];
if (post.message) {
alert('Message: ' + post.message);
} else if (post.attachment && post.attachment.name) {
alert('Attachment: ' + post.attachment.name);
}
}
});
};
// 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>
Nothing shows in the browser. There is no JavaScript errors in console (Opera 11). Why is it not working?
I had the same issue and realized that the example is not parsing the response correctly. The object has a property data which is actually the Array to be parsed.
Another point is that you need a token to do this operation. So your code should be:
<div id="fb-root"></div>
<script>
var fbToken; // Highly recommended to make it global
window.fbAsyncInit = function()
{
FB.init({
appId : 'MY_ID', // App ID
channelUrl : '//WWW.YOUR_DOMAIN.COM/channel.html', // Channel File
status : true, // check login status
cookie : true, // enable cookies to allow the server to access the session
xfbml : true // parse XFBML
});
FB.login(function(response)
{
if (response.authResponse)
{
fbToken = response.authResponse.accessToken; // Save it for another requests
FB.api('/platform/posts', {limit:3}, function(response){
for (var i=0, l=response.data.length; i<l; i++)
{
var post = response.data[i];
if (post.message)
{
alert('Message: ' + post.message);
} else if (post.attachment && post.attachment.name)
{
alert('Attachment: ' + post.attachment.name);
}
}
});
} else {
// User did not accept oAuth
}
});
}
// 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>
It looks like you're not logged in. You need to authenticate the user to get an oauth token in place first before you can run this part of the code:
FB.api('/platform/posts', { limit: 3 }, function(response) {
for (var i=0, l=response.length; i<l; i++) {
var post = response[i];
if (post.message) {
alert('Message: ' + post.message);
} else if (post.attachment && post.attachment.name) {
alert('Attachment: ' + post.attachment.name);
}
}
});
See: http://developers.facebook.com/docs/reference/javascript/FB.login/

Categories