Facebook login using the Javascript FB.getLoginStatus works in one case and does not work in anther.
This works:
//view
<script type="text/javascript">
function f1() {
FB.getLoginStatus(function(response) {
if (response.status === 'connected') {
// the user is logged in and has authenticated your
// app, and response.authResponse supplies
// the user's ID, a valid access token, a signed
// request, and the time the access token
// and signed request each expire
FB.api('/me', function(response) {
alert(response.name + " " + response.id);
name1 = response.name;
uid1 = response.id;
});
// var uid = response.authResponse.userID;
// var accessToken = response.authResponse.accessToken;
} else if (response.status === 'not_authorized') {
// the user is logged in to Facebook,
// but has not authenticated your app
} else {
// the user isn't logged in to Facebook.
}
});
}
</script>
<%= content_for :body_attributes, "onload='f1();'" %>
This does not work
// view
<script type="text/javascript">
function f1() {
// same definition as above
}
</script>
<script type="text/javascript"> {
f1()
}
</script>
I do not understand why the second code does not work. Thanks!
<script type="text/javascript">
{
f1()
}
</script>
Remove the braces and add a semicolon and you should be ok:
<script type="text/javascript">
f1();
</script>
This works:
//view
<script type="text/javascript">
function f1 {
FB.getLoginStatus(function(response) {
Hard to believe that this should work – because that’s not how you define a function in JavaScript. It’s missing the round brackets () after the function name.
[from comments] Doesn't FB.api have to be trigged by an event?
No, it doesn’t – it can be called from anywhere.
Just with methods that will (/might) create a popup window (FB.login, FB.ui) it is usually better to call them on user interaction such as a click, because otherwise modern browser’s popup blockers with default settings are likely to suppress the popup.
Related
I have searched for this and the answers were VERY unclear and outdated.
So - I am using Facebook Javascript SDK to allow people to log in and out of my site. When they log out, I want them to be able to stay logged in to Facebook.
I am using standard code:
<!DOCTYPE html>
<html>
<head>
<title>Facebook Login JavaScript Example</title>
<meta charset="UTF-8">
</head>
<body>
<script>
// This is called with the results from from FB.getLoginStatus().
function statusChangeCallback(response) {
console.log('statusChangeCallback');
console.log(response);
// The response object is returned with a status field that lets the
// app know the current login status of the person.
// Full docs on the response object can be found in the documentation
// for FB.getLoginStatus().
if (response.status === 'connected') {
// Logged into your app and Facebook.
testAPI();
} else if (response.status === 'not_authorized') {
// The person is logged into Facebook, but not your app.
document.getElementById('status').innerHTML = 'Please log ' +
'into this app.';
} else {
// The person is not logged into Facebook, so we're not sure if
// they are logged into this app or not.
document.getElementById('status').innerHTML = 'Please log ' +
'into Facebook.';
}
}
// This function is called when someone finishes with the Login
// Button. See the onlogin handler attached to it in the sample
// code below.
function checkLoginState() {
FB.getLoginStatus(function(response) {
statusChangeCallback(response);
});
}
window.fbAsyncInit = function() {
FB.init({
appId : '#######',
cookie : true, // enable cookies to allow the server to access
// the session
xfbml : true, // parse social plugins on this page
version : 'v2.2' // use version 2.2
});
// Now that we've initialized the JavaScript SDK, we call
// FB.getLoginStatus(). This function gets the state of the
// person visiting this page and can return one of three states to
// the callback you provide. They can be:
//
// 1. Logged into your app ('connected')
// 2. Logged into Facebook, but not your app ('not_authorized')
// 3. Not logged into Facebook and can't tell if they are logged into
// your app or not.
//
// These three cases are handled in the callback function.
FB.getLoginStatus(function(response) {
statusChangeCallback(response);
});
};
// 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/en_US/sdk.js";
fjs.parentNode.insertBefore(js, fjs);
}(document, 'script', 'facebook-jssdk'));
// Here we run a very simple test of the Graph API after login is
// successful. See statusChangeCallback() for when this call is made.
function testAPI() {
console.log('Welcome! Fetching your information.... ');
FB.api('/me', {fields: 'name,email'}, function(response) {
console.log('Successful login for: ' + response.name);
document.getElementById('status').innerHTML =
'Thanks for logging in, ' + response.name + '!';
});
}
</script>
<!--
Below we include the Login Button social plugin. This button uses
the JavaScript SDK to present a graphical Login button that triggers
the FB.login() function when clicked.
-->
<fb:login-button data-auto-logout-link="true" scope="public_profile,email" onlogin="checkLoginState();">
</fb:login-button>
<div id="status">
</div>
</body>
</html>
PERFECT! I figured it out on my own. The answer is two part. You need to revoke access. You do this like this in your javascript:
function logoutFacebook()
{
FB.getLoginStatus(function(response) {
if (response.status === 'connected') {
// the user is logged in and has authenticated your
// app, and response.authResponse supplies
// the user's ID, a valid access token, a signed
// request, and the time the access token
// and signed request each expire
var uid = response.authResponse.userID;
var accessToken = response.authResponse.accessToken;
FB.api('/'+uid+'/permissions', 'delete', function(response){});
} else if (response.status === 'not_authorized') {
// the user is logged in to Facebook,
// but has not authenticated your app
} else {
// the user isn't logged in to Facebook.
}
});
}
Then, you add a button to fire off that function:
<button id="logout" onclick="logoutFacebook()">Logout</button>
I'm trying to develop a Windows 8 app and I want to integrate Facebook in it.
I know this can be done without their SDK, but I've seen it can also be done with it and I'd love to go for the SDK.
I have the all.js file downloaded and referenced.
I included the initialization code in default.html:
<div id="fb-root"></div>
<script>
window.fbAsyncInit = function () {
// init the FB JS SDK
FB.init({
appId: '*******', // App ID from the app dashboard
status: true, // Check Facebook Login status
xfbml: true // Look for social plugins on the page
});
// Additional initialization code such as adding Event Listeners goes here
};
</script>
I'm trying to login using FB.login() when a button is pressed, but it's not working because
FB.getLoginStatus(function (response) {
console.log("entered")
if (response.status === 'connected') {
console.log("connected");
} else {
console.log("connecting");
FB.login(function (response) {
if (response.authResponse) {
console.log("connected");
} else {
console.log("canceled");
}
});
}
});
However, nothing happens when I click the button I attached this function to.
What can it be?
Any help is appreciated,
thanks!
<!DOCTYPE html>
<html>
<head>
<title>Facebook Login Example</title>
<meta charset="UTF-8">
</head>
<body>
<script>
// This is called with the results from from FB.getLoginStatus().
function statusChangeCallback(response) {
console.log('statusChangeCallback');
console.log(response);
// The response object is returned with a status field that lets the
// app know the current login status of the person.
// Full docs on the response object can be found in the documentation
// for FB.getLoginStatus().
if (response.status === 'connected') {
alert("hh");
// Logged into your app and Facebook.
testAPI();
} else if (response.status === 'not_authorized') {
// The person is logged into Facebook, but not your app.
document.getElementById('status').innerHTML = 'Please log ' +
'into this app.';
} else {
// The person is not logged into Facebook, so we're not sure if
// they are logged into this app or not.
document.getElementById('status').innerHTML = 'Please log ' +
'into Facebook.';
}
}
// This function is called when someone finishes with the Login
// Button. See the onlogin handler attached to it in the sample
// code below.
function checkLoginState() {
FB.getLoginStatus(function(response) {
statusChangeCallback(response);
});
}
window.fbAsyncInit = function() {
FB.init({
appId : '197393374008468',
cookie : true, // enable cookies to allow the server to access
// the session
xfbml : true, // parse social plugins on this page
version : 'v2.7' // use version 2.2
});
// Now that we've initialized the SDK, we call
// FB.getLoginStatus(). This function gets the state of the
// person visiting this page and can return one of three states to
// the callback you provide. They can be:
//
// 1. Logged into your app ('connected')
// 2. Logged into Facebook, but not your app ('not_authorized')
// 3. Not logged into Facebook and can't tell if they are logged into
// your app or not.
//
// These three cases are handled in the callback function.
FB.getLoginStatus(function(response) {
statusChangeCallback(response);
});
};
// 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 = "https://connect.facebook.net/en_US/all.js";
fjs.parentNode.insertBefore(js, fjs);
}(document, 'script', 'facebook-jssdk'));
// Here we run a very simple test of the Graph API after login is
// successful. See statusChangeCallback() for when this call is made.
function testAPI() {
console.log('Welcome! Fetching your information.... ');
FB.api('/me', function(response) {
console.log('Successful login for: ' + response.name);
document.getElementById('status').innerHTML =
'Thanks for logging in, ' + response.name + '!';
});
}
</script>
<!--
Below we include the Login Button social plugin. This button uses
the SDK to present a graphical Login button that triggers
the FB.login() function when clicked.
-->
<fb:login-button scope="public_profile,email" onlogin="checkLoginState();">
</fb:login-button>
<div id="status">
</div>
</body>
</html>
I am getting the common JS error "Uncaught Reference Error: FB is not defined "
There are a lot of questions on the same issue and I have tried each solution available on
stackoverflow but to no avail. Apparently, people seem to get this issue sometimes, I am getting it all the time. Can anyone spot an error ? I am not using a chnnel url file for the time being
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Untitled Document</title>
</head>
<body>
<div id="fb-root"></div>
<script type="text/javascript">
window.fbAsyncInit = function()
{
// init the FB JS SDK
FB.init=({
appId : 'xxxxxxxxxxx', // App ID from the App Dashboard
//channelUrl : 'www.something.in/channel.html', // Channel File for x-domain communication
status : false, // 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?
}) ;
// Additional initialization code such as adding Event Listeners goes here
} ;
</script>
<script type="text/javascript">
// Load the SDK's source Asynchronously
// Note that the debug version is being actively developed and might
// contain some type checks that are overly strict.
// Please report such bugs using the bugs tool.
(function(d, debug){
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" + (debug ? "/debug" : "") + ".js";
ref.parentNode.insertBefore(js, ref);
}(document, /*debug*/ false));
FB.getLoginStatus(function(response) {
if (response.status === 'connected') {
// the user is logged in and has authenticated your
// app, and response.authResponse supplies
// the user's ID, a valid access token, a signed
// request, and the time the access token
// and signed request each expire
var uid = response.authResponse.userID;
var accessToken = response.authResponse.accessToken;
alert(uid) ;
} else if (response.status === 'not_authorized') {
// the user is logged in to Facebook,
// but has not authenticated your app
alert("not authorised");
} else {
// the user isn't logged in to Facebook.
alert("NOTHING") ;
}
});
</script>
</body>
</html>
Can you get the basic example to work?
https://developers.facebook.com/docs/facebook-login/getting-started-web/
(the full text under section 3)
I could get the basic simple example to load BUT when I included my own code base FB was never defined.
It turned out to be the fact that I had prototyped "Object" to have a method called 'copyProperties'.
I changed that method to 'copyProps' and it all works now. So, if Facebook is prototyping Object for their own purposes then I'd guess there are some other potential collisions out there too.
Sure, this must be one reason everyone says not to prototype Object, but so convenient! Obviously, it's not enumerable, so don't yell at me too hard.
I had the same problem and I tried everything. I only solved it by requesting the Facebook script by jQuery and then initializing it:
$(document).ready(function()
{
$.getScript("http://connect.facebook.net/en_US/all.js#xfbml=1", function () {
FB.init({ appId: 'xxxxxxxx', status: false, cookie: true, xfbml: true });
});
});
FB.getLoginStatus(function(response) {
if (response.status === 'connected') {
// the user is logged in and has authenticated your
// app, and response.authResponse supplies
// the user's ID, a valid access token, a signed
// request, and the time the access token
// and signed request each expire
var uid = response.authResponse.userID;
var accessToken = response.authResponse.accessToken;
alert(uid) ;
} else if (response.status === 'not_authorized') {
// the user is logged in to Facebook,
// but has not authenticated your app
alert("not authorised");
} else {
// the user isn't logged in to Facebook.
alert("NOTHING") ;
}
});
Your code has a small mistake in FB.init=({.
You have to remove equal sign after FB.init and your code look like:
FB.init({
appId : 'xxxxxxxxxxx', // App ID from the App Dashboard
//channelUrl : 'www.something.in/channel.html', // Channel File for x-domain communication
status : false, // 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?
}) ;
One more mistake you have done . your div id is fb-root but at the time of initialize you declare facebook-jssdk id
just make sure both should be same
Hi I am writing a code to login the user through the facebook. I store all the function in a file along with other javascript function. I try calling login function from another javascript function and get following error: login is not defined. Here is the code for index.html
<html xmlns:fb="http://ogp.me/ns/fb#">
<head>
<script type="text/javascript" src="javascript.js"></script>
</head>
<body>
<div id="fb-root"></div>
Hi!
</body>
</html>
Here is javascript.js
window.fbAsyncInit = function() {
// init the FB JS SDK
FB.init({
appId : '213443452146381', // App ID from the App Dashboard
channelUrl : '//http://abc.in/', // Channel File for x-domain communication
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) {
if (response.status === 'connected')
{
alert('connected');
}
else if (response.status === 'not_authorized') {
alert('not_authorized');
login();
} else {
alert('chillonly');
login();
}
});
function login() {
FB.login(function(response) {
if (response.authResponse) {
alert('connected');
testAPI();
} else {
alert('not_connected_login');
testAPI();
}
});
}
function testAPI() {
console.log('Welcome! Fetching your information.... ');
FB.api('/me', function(response) {
console.log('Good to see you, ' + response.name + '.');
});
}
// Additional initialization code such as adding Event Listeners goes here
};
// Load the SDK's source Asynchronously
// Note that the debug version is being actively developed and might
// contain some type checks that are overly strict.
// Please report such bugs using the bugs tool.
(function(d, debug){
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" + (debug ? "/debug" : "") + ".js";
ref.parentNode.insertBefore(js, ref);
}(document, /*debug*/ false));
// ]]>
function sayhi()
{
alert('Hi');
login();
}
I doubt if the facebook jdk is getting loaded at all. Please suggest a way to achieve this.
The method login() is not accessible since it is in a local scope.
If you want function login() { to be used outside of that scope, you need to make it global or part of some global namespace.
Change
function login() {
to
window.login = function () {
First of all, move the functions out of the window.fbAsyncInit. They are not accessible since in the local scope.
Then, you can have a flag that will only set to true when the JS-SDK is loaded, and you can "block" any process outside the window.fbAsyncInit till the flag is set. Something like:
var isLoaded = false;
window.fbAsyncInit = function()
{
isLoaded = true;
...
...
}
function myFunc(myVar)
{
if(isLoaded)
{
// Do FB related stuff
}
}
I'm using facebook open graph, new api, and i can do this:
<fb:login-button show-faces="true" max-rows="9" perms="email" autologoutlink="true" onlogin="window.location = 'http://www.example.com/facebook/facebook_test/'"></fb:login-button>
but when i read the doc if i need more options in http://developers.facebook.com/docs/reference/javascript/FB.login says i can:
FB.login(function(response) {
if (response.session) {
if (response.perms) {
// user is logged in and granted some permissions.
// perms is a comma separated list of granted permissions
} else {
// user is logged in, but did not grant any permissions
}
} else {
// user is not logged in
}
}, {perms:'read_stream,publish_stream,offline_access'});
but if i need another image for fb button, and if i need another things, i can't find how do that, of in what part of html i can call FB.login, is between tags 'script'?
You need to use Javascript SDK for this. Just wrap that FB.login into some function and call it wherever you want. For example if you want to call it on image click:
<html>
<head>
</head>
<body>
<div id="fb-root"></div>
<script>
//initializing API
window.fbAsyncInit = function() {
FB.init({appId: 'your app id', status: true, cookie: true,
xfbml: true});
};
(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>
<!-- custom login button -->
<img src="images/my_login.png">
<script>
//your fb login function
function fblogin() {
FB.login(function(response) {
//...
}, {scope:'read_stream,publish_stream,offline_access'});
}
</script>
</body>
</html>