How to Reuse Facebook Access token to login using javascript sdk - javascript

I need to implement Facebook Connect With javascript sdk,Right now,I am able to Allow users to Login into my website using their facebook credentials..but the problem is Everytime the users visit my page it asks for facebook login..is it possible that already logged in users to allow to post,Share and access their profile details and friends list etc..automatically...Can anyone help me out with this.....Thank u in advance..
Currently My code is like this...
enter 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));
// Init the SDK upon load
window.fbAsyncInit = function () {
FB.init({
appId: 'xxxxxxxxxxxxx', // App ID
channelUrl: '//' + window.location.hostname + '/channel', // 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) {
if (me.name) {
document.getElementById('auth-displayname').innerHTML = me.name;
document.getElementById('UserEmail').innerHTML = me.email;
document.getElementById('UserGender').innerHTML = me.gender;
document.getElementById('AccessToken').innerHTML = response.authResponse.accessToken;
getPhoto();
}
})
document.getElementById('auth-loggedout').style.display = 'none';
document.getElementById('auth-loggedin').style.display = 'block';
} else {
// user has not auth'd your app, or is not logged into Facebook
document.getElementById('auth-loggedout').style.display = 'block';
document.getElementById('auth-loggedin').style.display = 'none';
}
});
$("#auth-logoutlink").click(function () { FB.logout(function () { window.location.reload(); }); });
function getPhoto() {
FB.api('/me/picture?type=normal', function (response) {
var str = "<br/> <img src='" + response.data.url + "'/>";
document.getElementById("ProfilePic").innerHTML = str;
});
}
}
</script>

This is way too complicated, you can just use FB.getLoginStatus instead of FB.Event.subscribe, it refreshes the Token automatically: https://developers.facebook.com/docs/reference/javascript/FB.getLoginStatus

Related

How do i get user_likes permission from Facebook developers?

I am developing one website in asp.net, it has an option called login through Facebook, and it has to allow login if and only if a user like my page on facebook. I have done all the procedures to get user_likes permission from the Facebook developer, even though if I fill all the procedures in user_likes page submit button is not activating, Can anyone help in this regard?
This is what have done in my code:
HTML source code:
<script>
(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));
window.fbAsyncInit = function () {
FB.init({
appId: '****************',
channelUrl: '//' + window.location.hostname + '/channel',
status: true,
cookie: true,
xfbml: true
});
FB.Event.subscribe('auth.statusChange', function (response) {
if (response.authResponse) {
FB.api({
method: "pages.isFan",
page_id: '****************',
}, function(response) {
console.log(response);
if(response){
window.location = "Default2.aspx";
} else {
window.location = "Default3.aspx";
}
});
document.getElementById('auth-loggedout').style.display = 'none';
document.getElementById('auth-loggedin').style.display = 'block';
} else {
document.getElementById('auth-loggedout').style.display = 'block';
document.getElementById('auth-loggedin').style.display = 'none';
}
});
$("#auth-logoutlink").click(function () { FB.logout(function () { window.location.reload(); }); });
}
</script>
the like option on objects and photos, were disabled by facebook in 2016, discussed with them (they were abused too). The user_likes option allows you to retrieve all the pages liked by the user.
In this case, you would have to use the facebook-like plugin. You can find more information about it here: https://developers.facebook.com/docs/android/like-button
I hope I've helped!

How to use Facebook API calls after the initial log in using the Javascript SDK

I just recently started to integrate Facebook onto the website I'm working on currently. What I have so far is that the user can login and I can get their information after the login. What I'm struggling to understand is how do I make FB.api() calls after the initial login html page? I know that the Javascript SDK automatically handles the Access Tokens and stuff but I am unsure of how to make use of it. What I have so far is:
window.fbAsyncInit = function()
{
FB.init({
appId : 'API_KEY', // Set YOUR APP ID
channelUrl : 'DOMAIN', // 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)
{
console.log("Authorization Change");
if (response.status === 'connected')
{
console.log("Connected to FaceBook");
//SUCCESS
}
else if (response.status === 'not_authorized')
{
console.log("Logged into Facebook but not us");
FacebookLogin();
//FAILED
}
else
{
console.log("Logged out of both");
FacebookLogin();
//UNKNOWN ERROR
}
});
};
function FacebookLogin()
{
FB.login(function(response)
{
if (response.authResponse)
{
window.location = "test.php";
}
else
{
console.log('User cancelled login or did not fully authorize.');
}
},{scope: 'email,user_birthday,read_friendlists'});
}
// 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));
All of this code is inside a script tag at the top of the login html page. What I'm going to do is once the user logs in and is authenticated I'm going to direct them to another page where I will use the FB.api() function to get their information and fill in the registration form for them. Any suggestions or tips?
you can use the following function to get information about user after the user is login successfully and display in any DOM element
function fqlQuery(){
FB.api('/me', function(response) {
var query = FB.Data.query('select name, hometown_location, sex, pic_square from user where uid={0}', response.id);
query.wait(function(rows) {
document.getElementById('name').innerHTML =
'Your name: ' + rows[0].name + "<br />" +
'<img src="' + rows[0].pic_square + '" alt="" />' + "<br />";
});
});
}
More examples can be found here

Facebook Login behaving weird

I have a site that has a login through facebook option
I can't figure out what's wrong, I'm getting two kinds of errors
The first, even though for me it works (Chrome, Explorer) my friend receives a "new_fb_login() not defined" error
And just now I started getting those ambiguous errors (chrome debug):
Unsafe JavaScript attempt to access frame with URL **facebooky URL** from
frame with URL http://site.co.il/. The frame being accessed set
'document.domain' to 'facebook.com', but the frame requesting access did not.
Both must set 'document.domain' to the same value to allow access.
I thought it might have something to do with my site currently password protected, because now when I put the password back I just started getting them, but after disabling back they didn't stop, maybe takes some time to refresh?...
I'd appreciate some light upon this, thanks!
this is my code, right after the tag
<div id="fb-root"></div>
<script>
function new_fb_login() { //
if(!fb_connected){
FB.login(function(response) {
if (response.authResponse) {
fb_connected = true;
console.log('connected'); //Approved the app just now
login(true);
} else {
fb_connected = false;
console.log('cancelled');
}
});
}
else{
FB.api('/me', function(response) {
login(true);
});
}
}
function testAPI() {
console.log('Logged');
FB.api('/me', function(response) {
console.log('Welcome, ' + response.name + '.');
});
}
window.fbAsyncInit = function() {
FB.init({
appId : 'MyActualCode', // App ID
channelUrl : '//WWW.site.CO.IL/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') {
console.log('connected');
fb_connected = true;
//testAPI();
} else if (response.status === 'not_authorized') {
fb_connected = false;
console.log('not_authorized');
//login();
} else {
console.log('not_logged_in');
fb_connected = false;
//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));

Facebook Registration - Reading the data/signed request with Javascript

I am able to get the registration form working with custom fields and retrieve the custom fields via a cookie on the redirect page. What I cannot figure out is how to retrieve the Facebook info (name,email,birthday) on the next page (I'm not a PHP guy). I have been over the documentation several times, the "reading the data" section (FB Documentation), and scoured the internet but can only find PHP and C# solutions.
I am looking for a javascript, jQuery, or ColdFusion solution if someone could help me out.
Below is my code as a quick reference. As it stands Page 2 just dumps out the cookie information.
Page 1
<html>
<head>
<title>My Facebook Login Page</title>
</head>
<body>
<!--- Facebook Call --->
<div id="fb-root"></div>
<script>
window.fbAsyncInit = function() {
FB.init({
appId : 'myAppID', // App ID
channelUrl : 'http://.../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
});
};
// 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>
<!--- Output Facebook Box--->
<fb:registration redirect-uri="http://.../page2.cfm"
fields='[
{"name":"name"},
{"name":"email"},
{"name":"displayName","description":"Display Name:", "type":"text"},
{"name":"location"},
{"name":"birthday"}
]'
onvalidate="validateAndSave">
</fb:registration>
<!---Validation + set Cookie --->
<script>
function validateAndSave(form) {
if (!form.displayName) {
return({"displayName":"Display Name is Required"});
}
document.cookie = 'fbInfo='+'displayName='+form.displayName;
return {};
}
</script>
</body>
Here is my implementation based on trial and error with the FB javascript API.
function checkFB()
{
if (typeof(FB) === "undefined")
{
var t = setTimeout("checkFB()", 1000);
if (debug) console.log("FB is still undefined, try again in 1 second.");
}
else
{
if (debug) console.log("FB is defined, try to login -> ");
//Function to check the current login status of facebook
FB.getLoginStatus(function(r)
{
if (r.status === "not_authorized")
{
if (debug) console.log("-> NOT AUTHORIZED ");
}
else if (r.status === "connected")
{
if (debug) console.log("-> connected ");
if (r.authResponse)
{
FB.api('/me', function(rr) {
document.getElementById("fbFname").value = rr.first_name;
document.getElementById("fbLname").value = rr.last_name;
document.getElementById("fbEmail").value = rr.email;
document.getElementById("fbID").value = rr.id;
document.getElementById("status").value = "OK";
});
submitFB();
}
else
{
document.getElementById("status").value = "NOT AUTHORIZED";
history.go(-1);
if (debug) console.log("NOT AUTHORIZED");
}
}
else
{
if (debug) console.log("-> not connected -> POP UP BOX expected ");
// start login process
FB.login(function(re)
{
if (re.authResponse)
{
FB.api('/me', function(rr) {
document.getElementById("fbFname").value = rr.first_name;
document.getElementById("fbLname").value = rr.last_name;
document.getElementById("fbEmail").value = rr.email;
document.getElementById("fbID").value = rr.id;
document.getElementById("status").value = "OK";
});
submitFB();
}
else
{
document.getElementById("status").value = "NOT AUTHORIZED";
history.go(-1);
if (debug) console.log("NOT AUTHORIZED");
}
},
{scope: 'email'}); // we define what information we want to get from the user
}
});
}
}
I hope you have already gotten an appID from facebook and have a channel file, they need to replace 'myAppID' and 'http://.../channel.html'.
FB.init({
appId : 'myAppID', // App ID
channelUrl : 'http://.../channel.html', // Channel File

Redirect URI using the Javascript SDK after authentication

So I've set up a basic login/authentication flow on the home page of my site. After the authentication dialog, I want to redirect them to another page on my site. I've tried several variations of the existing code, changing the site url under basic settings in the developer app, trying different oauth flows, and still, it simply redirects to the same homepage they logged in on. I know this sounds tremendously easy but there are so many different authentication flows and implementations that it's a bit confusing.
<div id="fb-root"></div>
<script>
window.fbAsyncInit = function() {
FB.init({
appId : 'XXXXXXXXXX', // App ID
channelURL : '//localhost/dataweavr/channel.php', // 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
});
// Additional initialization code here
};
// 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));
</script>
And then some more fun...
<div id="fb-root"></div>
<div id="user-info"></div>
<button id="fb-auth">Login</button>
<script>
window.fbAsyncInit = function() {
FB.init({ appId: 'XXXXXXXXXXXXXXXXXXXXXX',
status: true,
cookie: true,
xfbml: true,
oauth: true});
function updateButton(response) {
var button = document.getElementById('fb-auth');
if (response.authResponse) {
//user is already logged in and connected
var userInfo = document.getElementById('user-info');
FB.api('/me', function(response) {
userInfo.innerHTML = '<img src="https://graph.facebook.com/'
+ response.id + '/picture">' + response.name;
button.innerHTML = 'Logout';
});
button.onclick = function() {
FB.logout(function(response) {
var userInfo = document.getElementById('user-info');
userInfo.innerHTML="";
});
};
} else {
//user is not connected to your app or logged out
button.innerHTML = 'Login';
button.onclick = function() {
FB.login(function(response) {
if (response.authResponse) {
FB.api('/me', function(response) {
var userInfo = document.getElementById('user-info');
userInfo.innerHTML =
'<img src="https://graph.facebook.com/'
+ response.id + '/picture" style="margin-right:5px"/>'
+ response.name;
});
} else {
//user cancelled login or did not grant authorization
}
}, {scope:'email,user_birthday'});
}
}
}
// run once with current status and whenever the status changes
FB.getLoginStatus(updateButton);
FB.Event.subscribe('auth.statusChange', updateButton);
};
(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 another unrelated issue. Why do I only have a normal button popup? How can I get the SDK to render a Facebook login button rather than just a simple login button?
You should be able to redirect the user after the login response. Under these lines:
FB.login(function(response) {
if (response.authResponse) {
Add something like this:
window.top.location = "http://page_to_redirect";
The button thing, hmm... well, you are writing a simple login button in the html, if you want a login button, change this:
Login
To this:
<fb:login-button></fb:login-button>
Hope it helps.

Categories

Resources