Facebook Javascript SDK redirect not working - javascript

I'm trying to redirect a facebook user after he has logged in. For loging I used the sample code for jssdk from developers.facebook.com and then I added this to redirect a certain user.
var uid = response.authResponse.userID;
var accessToken = response.authResponse.accessToken;
if(uid == '**********'){
window.location.replace('http://stackoverflow.com/');
}
but it does not work.
here's the complete code:
<html>
<head></head>
<body>
<div id="fb-root"></div>
<script>
window.fbAsyncInit = function() {
FB.init({
appId : '************',
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. This event is fired
// for any authentication related change, such as login, logout or session refresh. This means that
// whenever someone who was previously logged out tries to log in again, the correct case below
// will be handled.
FB.Event.subscribe('auth.authResponseChange', function(response) {
// Here we specify what we do with the response anytime this event occurs.
if (response.status === 'connected') {
// The response object is returned with a status field that lets the app know the current
// login status of the person. In this case, we're handling the situation where they
// have logged in to the app.
var uid = response.authResponse.userID;
var accessToken = response.authResponse.accessToken;
if(uid == '**********'){
window.location.replace('http://stackoverflow.com/');
}
testAPI();
} else if (response.status === 'not_authorized') {
// In this case, the person is logged into Facebook, but not into the app, so we call
// FB.login() to prompt them to do so.
// In real-life usage, you wouldn't want to immediately prompt someone to login
// like this, for two reasons:
// (1) JavaScript created popup windows are blocked by most browsers unless they
// result from direct interaction from people using the app (such as a mouse click)
// (2) it is a bad experience to be continually prompted to login upon page load.
FB.login();
} else {
// In this case, the person is not logged into Facebook, so we call the login()
// function to prompt them to do so. Note that at this stage there is no indication
// of whether they are logged into the app. If they aren't then they'll see the Login
// dialog right after they log in to Facebook.
// The same caveats as above apply to the FB.login() call here.
FB.login();
}
});
};
// 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));
// Here we run a very simple test of the Graph API after login is successful.
// This testAPI() function is only called in those cases.
function testAPI() {
console.log('Welcome! Fetching your information.... ');
FB.api('/me', function(response) {
console.log('Good to see you, ' + 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 show-faces="true" width="200" max-rows="1"></fb:login-button>
</body>
</html>

You may have more luck if you try the more conventional
window.location = 'stackoverflow.com/';
on your successful uid comparison, rather than the replace() method.

Related

How to delay execution of JS functions until Facebook JS SDK has finished initializing

So, I am using the Facebook JavaScript SDK to allow users to login to my app. I am using the Facebook SDK in an HTML file along with another JavaScript file. The second JS file accesses the FB object from inside the SDK. The HTML is basically set up like so
<!DOCTYPE HTML>
<html>
<body>
<script src = 'FacebookSDK.js' type = 'text/javascript'></script>
</body>
<script src = 'Controller.js' type = 'text/javascript'></script>
</html>
When I try to access the FB object inside the Controller.js file like so
FB.getLoginStatus(function(response) {
console.log(response.authResponse.userID);
});
I get an error saying
pollcreationClient.js:4 Uncaught ReferenceError: FB is not defined
So, clearly my Controller.js file is executing before the Facebook SDK has initialized. I thought setting the second JS file to load outside the body tag would provide enough time for the SDK to load and initialize. But, this clearly isn't the case. What do I do to make sure that my Controller.js file function, where I call the FB object, doesn't execute until the SDK file has finished executing?
For reference, here is the Facebook SDK file
// 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: '332044557128106',
cookie: true, // enable cookies to allow the server to access
// the session
xfbml: true, // parse social plugins on this page
version: 'v2.5' // use graph api version 2.5
});
// 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 + '!';
});
}
I found a quick workaround to my problem.
NOTE: It doesn't provide a perfect solution, more of a patchwork job. I didn't use the solutions mentioned in the comments because they didn't work in my situation. Hopefully this might be useful to someone else.
Found this answer here
How to workaround 'FB is not defined'?
if (typeof FB !== 'undefined' && FB !== null) {
FB.Event.subscribe('auth.authResponseChange', function() {
FB.getLoginStatus(function(response) {
console.log('Response from in here');
console.log(response);
$('.submit-butt').on('click', function() {
console.log('From in here');
ajaxFunctions.ready(ajaxFunctions.ajaxRequest('POST', appUrl + '/poll-create', response.authResponse, function(data) {
}));
});
});
});
}else{
location.reload();
}
Basically, this checks whether the FB object is defined and exists. If it does, it runs the code and if it doesn't I've set the page to reload. This works for me because my issue was that it was in certain situations where the FB object was not being defined, whereas it worked at other times. Again, this is not a great solution but it does the job for me.

Facebook javascript SDK login https: works only if you login twice

EDIT: please check the workaround at the end of this question.
There are a lot of similar threads but I cannot find the same problem.
Basically, we moved our login page to HTTPS.
When the page was HTTP, everything was working great, without problems.
The flow was:
The user opens the login page
The user clicks on the Facebook login button
The user performs the FB authentication
The user is redirected to PAGE2
Now the flow is:
The user opens the login page
The user clicks on the Facebook login button
The user performs the FB authentication
The user is redirected on the login page again!
The user clicks on the Facebook login button
The user is redirected to PAGE2
So, the user has to perform the operation twice.
The code:
window.fbAsyncInit = function () {
FB.init({appId: HERE_MY_APP_ID,
status: true,
cookie: true,
xfbml: true,
oauth: true});
FB.getLoginStatus(function (response) {
console.log(JSON.stringify(response));
if (response.status == 'connected') {
// Something here
}
});
};
(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/it_IT/all.js";
d.getElementsByTagName('head')[0].appendChild(js);
}(document));
And this is the function called when the user clicks on the Facebook button:
function fblogin() {
FB.login(function (response) {
if (response.status == 'connected') {
login();
} else {
// user is not logged in
window.location.reload();
}
}, {scope: 'email,publish_stream'});
return false;
}
Please note that debugging this code, the response printed in the getLoginStatus function says that response.status is unknown the first time, but when the page reloads, the response object is filled correctly, with response.status that is connected!.
How can I debug this issue? Any hints?
** WORKAROUND **
I've moved the getLoginStatus code from fbAsyncInit to the FB.login callback and now it works. But it's just a workaround, probably.

Facebook login works fine in browser but doesn't work on android with phonegap

After about 2 days of trying to implement every version of the phonegap facebook plugin i decided to give up on it and to implement plain JS login system in my app. To be honest, native login system is just not worth handling this plugin...
I followed the instructions on the facebook developer site and my login works perfectly on desktop browsers. The problem begins after i compile it with phonegap and try to run it on an android device.
When i Press the login button I'm getting a
"FB is not defined at..."
this results from the attempt to access the FB.login() method.
Relevant code is :
window.fbAsyncInit = function() {
FB.init({
appId : 'XXXXXXXXXX', // contains my App ID
channelUrl : 'YYYYYYYYYYYY', // contains my Channel File
status : true, // check login status
cookie : true, // enable cookies to allow the server to access the session
xfbml : true // parse XFBML
});
FB.Event.subscribe('auth.authResponseChange', function(response) {
// Here we specify what we do with the response anytime this event occurs.
if (response.status === 'connected') {
testAPI();
active_access_token = response.authResponse.accessToken;
$.mobile.changePage("#main_page");
} else if (response.status === 'not_authorized') {
FB.login();
} else {
FB.login();
}
});
};
// Load the SDK asynchronously
(function(d){
console.log ("async load started!");
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 testAPI() {
console.log('Welcome! Fetching your information.... ');
FB.api('/me', function(response) {
console.log('Good to see you, ' + response.name + '.');
});
}
Button wiring:
function set_buttons() {
$("#facebook_login_button").click(function(){
console.log("login attempt");
FB.login();
});
Again, This works perfectly in browser. I just cant make it work on android after phonegap compile.
Ideas?
Well , i figured it out...
since I'm running it from a locahost I added "http:" to
js.src = "//connect.facebook.net/en_US/all.js";
So now it's:
js.src = "http://connect.facebook.net/en_US/all.js";
Try to go to your Facebook´s app > Setting > Advanced and add the correct urls on 'Valid OAuth redirect URIs'
For me it had to do with adding BundleID on developers facebook app settings under iOS section.
This may help some other person in my boat.

How do I request permissions for users information?

I think this is a very obvious question, but I am completely stumped. I think I have setup my app settings correctly, but when I try to authenticate (with Javascript SDK) my account on my website and then console.log(me), I still only get public information.
EDIT: I think that my problem is that my website is using the "Current Dialog" and not the "Referral Dialog." I understand that the referral dialog is only used when someone is directed to my website through Facebook, but I know there must be a way to use the Referral Dialog from my website as well. Why would anyone even use the Current Dialog if it can only authenticate the server with a user's public information? I read another post that said I should look at the authentication doc (https://developers.facebook.com/docs/authentication/), but as far as I can see there is nothing there on authorizing with the Referral Dialog.
I want to use Javascript SDK. Is this possible or will I have to just do it without Javascript SDK?
In Auth Dialog, I have this: email, user_about_me, user_likes, user_location, user_website, user_checkins
Here is my code:
// 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));
// Init the SDK upon load
window.fbAsyncInit = function() {
FB.init({
appId : '464723870207650', // App ID
channelUrl : '//'+window.location.hostname+'/scripts/channel.php', // Path to your Channel File
status : true, // check login status
cookie : true, // enable cookies to allow the server to access the session
xfbml : true // parse XFBML
});
// listen for and handle auth.statusChange events
FB.Event.subscribe('auth.statusChange', function(response) {
if (response.authResponse) {
// user has auth'd your app and is logged into Facebook
FB.api('/me', function(me){
console.log(me);
})
} else {
// user has not auth'd your app, or is not logged into Facebook
}
});
}
When I run it through the debugger, I don't get any errors.
Just call the FB.login method along with the wanted permissions:
function login() {
FB.login(function(response) {
console.log("FB.login callback, response: ", response);
}, { scope: "email,publish_stream,etc" });
}
Just keep in mind that:
Calling FB.login results in the JS SDK attempting to open a popup
window. As such, this method should only be called after a user click
event, otherwise the popup window will be blocked by most browsers.

Facebook auth page doesn't close or refresh parent

Facebook authentication is working great. I can pull the profile pic and name of the user. However, when you click login and the facebook prompt comes up I have two problems (in both IE and Chrome).
First off, the window never closes. It just goes to a blank white page. This is actually happening to me across the web. turntable.fm logins do this as well as any fb connected sites I can think of. it happens to me at work, at home on multiple different PCs. Is fb broken? I can't help but think this is related to the other issue...
My page doesn't refresh after I close the (blank) login popup.
So those are the issues. I tried subscribing to the auth.login event and calling a reload() there, which is what the documentation recommends, but this didn't refresh when you logged in. It also caused a problem where if you logged out it would just automatically log you back in. That's why I added the code below to detect a logout and reload. That actually works. So how can I make it reload when the popup window is closed, or even better, make the popup window close itself and reload my page?!
all relevant fb code below (I think):
window.fbAsyncInit = function () {
FB.init({
appId: '123456', // App ID
channelURL: 'http://www.mydomain.net/channel.html', // Channel File
status: true, // check login status
cookie: true, // enable cookies to allow the server to access the session
oauth: true, // enable OAuth 2.0
xfbml: true // parse XFBML
});
//update guest/username if logged in or not
FB.getLoginStatus(function (response) {
if (response.authResponse) {
FB.api('/me', function (response) {
$('#UserMenu').show();
$('#Login').hide();
$('#fbpic').html('<img alt="Account Picture" src="https://graph.facebook.com/' + response.username + '/picture" />');
$('#AccountName').html(response.name);
getVentID(response.id, response.name);
$('#Logout').show();
});
} else {
//not logged in to facebook
}
});
$('#Logout').live('click', function () {
FB.logout(function (response) {
// user is now logged out
window.location.reload();
});
});
//subscribe to login changes
FB.Event.subscribe('auth.login', function (response) {
});
};
// 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));
This was because I had Facebook "installed" in Chrome! Uninstall and now it works everywhere. SOOO happy!

Categories

Resources