i have implemented facebook log in using Facebook javascript SDK in Jquery mobile , now the problem is i want to persist connection through out all the pages as when ever i refresh the page i need to fire FB.Login again.
Moreover do i need to include following code in every html page to access the FB object ?
<script>
window.fbAsyncInit = function() {
FB.init({
appId : 'XXXXXXXXXX', // App ID
status : true, // check login status
cookie : true, // enable cookies to allow the server to access the session
xfbml : true // parse XFBML
});
// Additional initialization code here
};
// Load the SDK Asynchronously
(function(d){
var js, id = 'facebook-jssdk'; if (d.getElementById(id)) {return;}
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);
}(document));
</script>
Yes. You should include initialization of JavaScript SDK on every page.
JavaScript SDK should set cookie automatically (as you set in FB.init call parameters) so you doesn't need to call FB.login on every page
On each page, you will want to include the Javascript SDK.
On each page in the window.fbAsyncInit = function() {};, after calling the normal FB.init() you will want to call FB.getLoginStatus() (see: https://developers.facebook.com/docs/reference/javascript/FB.getLoginStatus/) which will give you the access token for you to use to access the API.
If you call init more than once the SDK responds with 'FB.init has already been called - this could indicate a problem' in your console log. To avoid that you can test for whether the FB object exists and then load and init the API if it does not.
$( document ).delegate("#my_jqm_page", "pagebeforecreate", function() {
if (typeof FB !== 'undefined') {
console.log("FB JS API is available now");
FB.getLoginStatus(function(response) {
if (response.status === 'connected') {
// etc.
Related
This question already has answers here:
Javascript Parse Facebook Login Issue
(4 answers)
Closed 6 years ago.
I want my website to login with facebook but I am seeing this error.
Given URL is not whitelisted in Client OAuth Settings: This redirect failed because the redirect URI is not whitelisted in the app’s Client OAuth Settings. Make sure Client and Web OAuth Login are on and add all your app domains as Valid OAuth Redirect URIs.
<!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: 'XXXXXXXXXXXX',
cookie : true, // enable cookies to allow the server to access
// the session
xfbml : true, // parse social plugins on this page
version : 'v2.5' // 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', 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 scope="public_profile,email" onlogin="checkLoginState();">
</fb:login-button>
<div id="status">
</div>
</body>
</html>
You must make sure you have registered your app with the developer page
Go here
For the facebook login docs
Go here
Then when you register your app make sure whatever URL you are using as the redirect page is the same as your app is sending too.
For example
http://example.com
is not,
http://www.example.com
To settup url as the local host refer to
this post
Please make sure you are setting your
$app_id = "xxx";
$app_secret = "xxx";
$my_url ="http://localhost:3080/example.php";
All to the correct data as specified inside your app settings when you create your app on facebook's developer page.
To make this as clear as possible.
Go to your app page and enter the url of the page in your localhost.
Then go to your code and add the exact same url.
in app settings,
http://localhost
in your code
http://localhost
If there is a port number after your localhost,
in app settings,
http://localhost:8080
in your code
http://localhost:8080
If there is a file after your localhost
in app settings,
http://localhost/myfile.php
in your code
http://localhost/myfile.php
Please try this code. replace your code with this code and do not forget to change the
YOUR_FACBEOOK_APP_ID
to your own.
<div id="fb-root"></div>
<script>
window.fbAsyncInit = function() {
FB.init({
appId: 'xxxxxxxxxxxxx',
status: true,
cookie: true,
xfbml: true
});
};
// 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));
function login() {
FB.login(function(response) {
// handle the response
console.log("Response goes here!");
}, {scope: 'read_stream,publish_stream,publish_actions,read_friendlists'});
}
function logout() {
FB.logout(function(response) {
// user is now logged out
});
}
var status = FB.getLoginStatus();
console.log(status);
</script>
<button onclick="javascript:login();">Login Facebook</button>
<br>
<button onclick="javascript:logout();">Logout from Facebook</button>
In my case, modifying the /etc/hosts file to map '127.0.0.1' to something like myapp.com - so that your application has a “real” URL, resolved the issue.
Same is to be added to "Valid OAuth redirect URIs" in the Client OAuth Settings.
I has the same problem .
For me the solution was to add both WWW and no-WWW versions of my site to whitelist in Client OAuth Settings.
I am trying to request additional permissions at the time of a facebook login using Facebook's suggested Javascript SDK. I am using the scope parameter to make the additional request as a part of the FB.login(). My chrome browser has blocked popups. When I load the page containing the FB.login and the scope parameters into my browser, Chrome blocks the automatic popup. When I then click on an html button to perform the facebook login and authorization request, the only permissions that the fb popup shows is the one for basic info. However, if I allow popups, then when I load the page, a facebook authorization popup automatically displays without the need to click on the button to launch the fb login. When this automatic popup displays, it now shows the additional permissions I included in the scope parameters. How can I get the additional permissions to display in the fb login popup when popups are blocked?
Below is my code:
<!DOCTYPE html>
<html>
<head>
<div id="fb-root"></div>
<script>
// Additional JS functions here
window.fbAsyncInit = function() {
FB.init({
appId : 'MY_APP_ID', // App ID
channelUrl : '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
});
// Additional init code here
FB.getLoginStatus(function(response) {
if (response.status === 'connected') {
// connected
} else if (response.status === 'not_authorized') {
// not_authorized
login();
} else {
// not_logged_in
login();
}
});
};
function login() {
FB.login(
function(response) {
if (response.authResponse) {
// connected
} else {
// cancelled
}
},
{scope: 'email, user_birthday'}
);
}
// 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>
</head>
<body>
<button type="button" onclick="FB.login()">login</button>
</body>
</html>
FB.login can not be used outside of an event handler (user initiated) due to it creating a popup when used outside of Canvas.
Instead, display a button that the user can click in order to execute FB.login.
The reason why your button does not ask for permissions is simply because you havent added any to the function call - you use FB.login() - no perms there.
I have implemented a Facebook based login.
The FB.login works perfectly, but the FB.logout doesn't. I have tried with different FB.init, deleting cookies, running the logout page several times in a row, but the only way to log my user out is in facebook itself.
The code I'm using for logout is:
<div id="fb-root"></div>
<script src="http://connect.facebook.net/en_US/all.js"></script>
<script>
FB.init({
appId: '***************',
xfbml: true,
status: true,
cookie: true
});
FB.getLoginStatus();
FB.logout();
</script>
Any ideas?
Thank you
did you tried having some button onclick event is FB.logout();
function logout(){
FB.logout(function(response) {
// user is now logged out
});
}
<button onclick="logout()">LogOut</button>
Try This
Try to do this:
<div id="fb-root"></div>
<script>
window.fbAsyncInit = function() {
FB.init({
appId : 'YOUR_APP_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
});
// Additional initialization code here
};
// 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>
and then call the FB.logout(). FB must be initializad before.
From the documentation:
This code loads the SDK asynchronously so it does not block loading other elements of your page. This is particularly important to ensure fast page loads for users and SEO robots.
The URLs in the above code are protocol relative. This lets the browser to load the SDK over the same protocol (HTTP or HTTPS) as the containing page, which will prevent "Insecure Content" warnings.
The function assigned to window.fbAsyncInit is run as soon as the SDK is loaded. Any code that you want to run after the SDK is loaded should be placed within this function and after the call to FB.init. For example, this is where you would test the logged in status of the user or subscribe to any Facebook events in which your application is interested.
Could suggest a way to authorize my web application in Facebook to get access_token with no need for redirect? I found out that this in fact is possible with deprecated Facebook REST API, but I cannot register new application to use it.
Regards,
ToM
You can only accomplish this with the facebook javascript library. With the PHP library, you are stuck with redirecting them to facebook... If they cancel out on facebook, they are now off your site.
With the javascript library, you get a modal window that if they cancel out of, just stay on your page.
Here's a short blurb on how to make the javascript button appear on your page and do a simple login check:
<div id="fb-root"></div>
<script>
window.fbAsyncInit = function() {
// Initialize Facebook Connect
FB.init({
appId : 'YOUR_FACEBOOK_APP_ID_HERE',
status : false, // Check login status
cookie : true, // Enable cookies to allow the server to access the session
xfbml : true, // Parse XFBML
oauth : true
});
};
// Get Facebook Connect JS and append it to the DOM
(function() {
var e = document.createElement('script');
e.async = true;
e.src = document.location.protocol+'//connect.facebook.net/en_US/all.js#xfbml=1';
document.getElementById('fb-root').appendChild(e);
}());
function fbLoginCheck(response){
if(response.status != 'unknown'){
//reload or redirect once logged in...
window.location.reload();
}
}
</script>
<a class="fb_button fb_button_medium"
onclick='FB.login(fbLoginCheck,{ scope: "user_about_me,user_location,user_birthday,email,publish_stream"})'>
<span class="fb_button_text">Join with Facebook</span></a>
I am developing a facebook (iframe) app.
I have included following code at bottom of my page:
<script>
window.fbAsyncInit = function() {
FB.Canvas.setAutoResize();
FB.init({
appId : '<?php echo FACEBOOK_APP_ID; ?>',
session : '<?php echo json_encode($session); ?>',
status : true,
cookie : true,
xfbml : true
});
// whenever the user logs in / out, we refresh the page
FB.Event.subscribe('auth.login', function() {
window.location.reload();
});
FB.Event.subscribe('auth.logout', function() {
window.location.reload();
});
};
(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);
}());
</script>
The problem here is, it seems that auth.login and auth.logout events are getting fired immediately inside window.fbAsyncInit function, even if I do not log-out from (or log-in to if logged out) my facebook profile.
I am doing no such action, even then these events seem to get fired, which causes their handler functions to reload my app (window.location.reload();), and the app goes into infinite reload loop.
Please guide me.
Thanks
From my experience instead of using auth.logout and auth.login events you may try the following code:
FB.Event.subscribe('auth.authResponseChange', function(response) {
FB.getLoginStatus(function(response) {
if (response.status === 'connected') {
// the user is logged in and connected to 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;
} else if (response.status === 'not_authorized') {
// the user is logged in to Facebook,
//but not connected to the app
} else {
// the user isn't even logged in to Facebook.
}
});
});
I've been stuck trying to solve this bug for a few days. The thing is that auth.login event is fired when the SDK is loaded even if you're already connected thus creating an infinite loop. I've solved it when i made the code listen to the authlogin event and reloading the page only if the user is not connected.
<script type="text/javascript">
window.fbAsyncInit = function() {
FB.init({
appId : '<?php echo AppInfo::appID(); ?>', // App ID
channelUrl : '//<?php echo $_SERVER["HTTP_HOST"]; ?>/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
});
// Listen to the auth.login which will be called when the user logs in
// using the Login button
FB.getLoginStatus(function(response) {
console.log (response.status);
//this is useful if you want to avoid the infinite loop bug
//it only reloads page when you log in
if (response.status != 'connected') {
FB.Event.subscribe('auth.login', function(response) {
// We want to reload the page now so PHP can read the cookie that the
// Javascript SDK sat. But we don't want to use
// window.location.reload() because if this is in a canvas there was a
// post made to this page and a reload will trigger a message to the
// user asking if they want to send data again.
//window.location = window.location;
//Im using the window.location.reload()
window.location.reload();
});
}
});
FB.Canvas.setAutoGrow();
};
// 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/all.js";
fjs.parentNode.insertBefore(js, fjs);
}(document, 'script', 'facebook-jssdk'));
</script>
Hope this works!
Anyway this is not the only problem i have. please check this post and help me if you can
impossible to read $_SESSION vars on PHP facebook app