FB api with firebase - facebook

I am having difficulty figuring out how to link a facebook account with an existing firebase email/password account. I can link it but then have no clue how to make calls to the FB api. Or i can not have it linked and used the FB api itself to make the login. I really want to be able to link the account to an existing email/password account.
var facebook = document.getElementById('facebook');
//var twitter = document.getElementById('twitter');
//var google = document.getElementById('google');
var fbunlink = document.getElementById('fbunlink');
//var twitunlink = document.getElementById('twitunlink');
//var googleunlink = document.getElementById('googleunlink');
var fbList = document.getElementById('fbList');
var provider = "";
var fbToken = "";
var fbId = [];
var fbName = [];
var fbLength = 0;
var fbAccessToken ="";
var fbUID = "";
var auth = firebase.auth();
var user = firebase.auth().currentUser;
window.fbAsyncInit = function() {
FB.init({
appId : '1899992333573742',
xfbml : true,
version : 'v2.10'
});
FB.AppEvents.logPageView();
FB.getLoginStatus(function(response) {
if (response.status === 'connected') {
var uid = response.authResponse.userID;
var accessToken = response.authResponse.accessToken;
} else if (response.status === 'not_authorized') {
} else {
}
});
};
(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'));
facebook.addEventListener('click', e => {
provider = new firebase.auth.FacebookAuthProvider();
provider.addScope('email');
provider.addScope('user_photos');
provider.addScope('publish_pages');
provider.addScope('business_management');
provider.addScope('read_insights');
provider.addScope('manage_pages');
provider.addScope('public_profile');
auth.currentUser.linkWithRedirect(provider);
firebase.auth().getRedirectResult().then(function(result) {
if (result.credential) {
// This gives you a Facebook Access Token. You can use it to access the Facebook API.
var token = result.credential.accessToken;
var credential = result.credential;
var user = result.user;
// ...
}
document.getElementById('fbunlink').style.visibility = 'visible';
document.getElementById('fbList').style.visibility = 'visible';
document.getElementById('facebook').style.visibility = 'hidden';
document.getElementById('status').innerHTML = 'You are logged in.';
getInfo();
}).catch(function(error) {
// Handle Errors here.
var errorCode = error.code;
var errorMessage = error.message;
// The email of the user's account used.
var email = error.email;
// The firebase.auth.AuthCredential type that was used.
var credential = error.credential;
// ...
});
});
/*
FB.login(function(response) {
if (response.status === 'connected') {
document.getElementById('fbunlink').style.visibility = 'visible';
document.getElementById('fbList').style.visibility = 'visible';
document.getElementById('facebook').style.visibility = 'hidden';
document.getElementById('status').innerHTML = 'You are logged in.';
var uid = response.authResponse.userID;
var accessToken = response.authResponse.accessToken;
fbAccessToken = uid;
fbUID = accessToken;
getInfo();
linkInfo();
} else if (response.status === 'not_authorized') {
document.getElementById('fbunlink').style.visibility = 'hidden';
document.getElementById('facebook').style.visibility = 'visible';
document.getElementById('fbList').style.visibility = 'hidden';
document.getElementById('status').innerHTML = 'You have logged out of Facebook.';
} else {
document.getElementById('status').innerHTML = 'You are not logged in.';
document.getElementById('facebook').style.visibility = 'visible';
document.getElementById('fbunlink').style.visibility = 'hidden';
document.getElementById('fbList').style.visibility = 'hidden';
}
}, {scope: 'email, user_photos, publish_pages, business_management, read_insights, manage_pages, public_profile'});
});*/
fbunlink.addEventListener('click', e => {
var user = firebase.auth().currentUser;
user.unlink("facebook.com");
document.getElementById('picture').innerHTML = "";
document.getElementById('status').innerHTML = 'You are not logged in.';
document.getElementById('facebook').style.visibility = 'visible';
document.getElementById('fbunlink').style.visibility = 'hidden';
document.getElementById('fbList').style.visibility = 'hidden';
});
function getInfo(){
FB.api('/me/accounts?limit=200', 'GET', {fields: 'business, name, data, id, picture', access_token : fbToken}, function(response){
document.getElementById('status').innerHTML = "";
console.log(response.data);
fbLength = response.data.length;
for(var i = 0; i < fbLength; i++){
fbId.push(response.data[i].id);
fbName.push(response.data[i].name);
document.getElementById('status').innerHTML += "<img src='https://graph.facebook.com/" + fbId[i] + "/picture?type=square'>" + " " + "<input type=" + "'checkbox'" + " id=" + "'" + fbId[i] + "'" + " value=" + "'" + fbId[i] + "'" + ">" + fbName[i] + "<br>";
}
});
}
/*function linkInfo(){
var credential = firebase.auth.FacebookAuthProvider.credential(fbUID, fbAccessToken);
auth.currentUser.link(credential).then(function(user) {
console.log("Account linking success", user);
}, function(error) {
console.log("Account linking error", error);
});
}*/
fbList.addEventListener('click', e => {
document.getElementById('picture').innerHTML = "";
for(var i = 0; i < fbLength; i++){
var temp = document.getElementById(fbId[i]);
if(temp.checked){
document.getElementById('picture').innerHTML += "<img src='https://graph.facebook.com/" + fbId[i] + "/picture?type=square'>" + " " + fbName[i] + "<br>";
}
}
});

So it seems you need to make calls to the Facebook API, so continue using Facebook API as Firebase Auth doesn't manage OAuth tokens and you need the FB API to do that for you.
In order to link the Facebook account to an email/password account, you need to use the Facebook API to get the FB user's OAuth access token.
You then link that to the currentUser:
firebase.auth().currentUser.linkWithCredential(firebase.auth.FacebookAuthProvider.credential(fbAccessToken))
This links that Facebook user to the email/password currentUser.

Related

Facebook app login issues from public user

I created Facebook app and integrated with magento, when public user try to login to the fb it shows this error.
]1
My requirement is when user login Facebook from magento site need to display user images and albums, but this process working with admin details (Getting the profile images and albums from admin details )
window.fbAsyncInit = function() {
FB.init({ appId: facebook_app_id,
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
document.getElementById("fbaccesstoken").value = response.authResponse.accessToken;
var userInfo = document.getElementById('user-info'),
photos_album = document.getElementById('photos_album');
FB.api('/me', function(response) {
/* userInfo.innerHTML = '<img src="https://graph.facebook.com/'
+ response.id + '/picture" />' + response.name;
button.innerHTML = 'Logout';*/
});
FB.api('/me/albums', function(response){
var l=response.data.length,
rs_all,
all_img;
if(l > 0){
rs_all ='<select id="fb_album" onchange="get_all_photos(this.value)"><option value="0">-- Select your album --</option>';
for (var i=0; i<l; i++){
var album = response.data[i],
albumid = album.id;
rs_all += '<option value="'+album.id+'">'+album.name+'</option>';
}
rs_all += '</select>';
userInfo.innerHTML = rs_all;
}
//
});
get_all_photos = function(id){
if(id==0){
photos_album.innerHTML = '';
return;
}
FB.api("/"+id+"/photos",function(response){
console.log(response);
var photos = response["data"],
pt_result = '<ul>';
for(var pt=0;pt<photos.length;pt++) {
console.log(photos[pt].images);
//pt_result += '<li><img color="" src="'+photos[pt].images[0].source+'" /></li>';
//pt_result += '<li><img color="" src="https://graph.facebook.com/' + photos[pt].id + '/picture'+'" /></li>';
pt_result += '<img src="https://graph.facebook.com/'+photos[pt].id + '/picture?access_token='+document.getElementById("fbaccesstoken").value+'" style="margin-right:5px"/>';
}
photos_album.innerHTML = pt_result+'</ul>';
});
}
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 = 'Please Login Facebook';
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:'user_photos'});
}
}
}
// run once with current status and whenever the status changes
FB.getLoginStatus(updateButton);
FB.Event.subscribe('auth.statusChange', updateButton);
};
window.fbAsyncInit = function() {
FB.init({ appId: facebook_app_id,
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
document.getElementById("fbaccesstoken").value = response.authResponse.accessToken;
var userInfo = document.getElementById('user-info'),
photos_album = document.getElementById('photos_album');
FB.api('/me', function(response) {
/* userInfo.innerHTML = '<img src="https://graph.facebook.com/'
+ response.id + '/picture" />' + response.name;
button.innerHTML = 'Logout';*/
});
FB.api('/me/albums', function(response){
var l=response.data.length,
rs_all,
all_img;
if(l > 0){
rs_all ='<select id="fb_album" onchange="get_all_photos(this.value)"><option value="0">-- Select your album --</option>';
for (var i=0; i<l; i++){
var album = response.data[i],
albumid = album.id;
rs_all += '<option value="'+album.id+'">'+album.name+'</option>';
}
rs_all += '</select>';
userInfo.innerHTML = rs_all;
}
//
});
get_all_photos = function(id){
if(id==0){
photos_album.innerHTML = '';
return;
}
FB.api("/"+id+"/photos",function(response){
console.log(response);
var photos = response["data"],
pt_result = '<ul>';
for(var pt=0;pt<photos.length;pt++) {
console.log(photos[pt].images);
//pt_result += '<li><img color="" src="'+photos[pt].images[0].source+'" /></li>';
//pt_result += '<li><img color="" src="https://graph.facebook.com/' + photos[pt].id + '/picture'+'" /></li>';
pt_result += '<img src="https://graph.facebook.com/'+photos[pt].id + '/picture?access_token='+document.getElementById("fbaccesstoken").value+'" style="margin-right:5px"/>';
}
photos_album.innerHTML = pt_result+'</ul>';
});
}
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 = 'Please Login Facebook';
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:'user_photos'});
}
}
}
// run once with current status and whenever the status changes
FB.getLoginStatus(updateButton);
FB.Event.subscribe('auth.statusChange', updateButton);
};
First of all, as the error message tells you, your App is in development mode. Got to the "Status & Review" tab of your App and use the switch next to this text:
Do you want to make this app and all its live features available to the general public?
That being said, you need to go through a review process with user_photos or that permission will only work for users with a role in your App. Everything you need to know about Login Review can be found here: https://developers.facebook.com/docs/facebook-login/review
Btw, you don´t need getLoginStatus AND subscribing to the event auth.statusChange. Here is a tutorial with detailed explanation about everything you need for login and refreshing the Access Token for returning users: http://www.devils-heaven.com/facebook-javascript-sdk-login/

Log in with facebook in app using jquery mobile

I am Making an Android App with the help of(jquery mobile) in which in need your help if i want to login with facebook in my app how i can do these thing please help me out
in have AppID and AppSecret
please explain me in step to step process
1) Add ChildBrowser Phongap Plugin for android in your app.
2) Your login page add this code
$("#btn_log_facebook").on("click", function(event){
if(event.handled !== true) {
var fb = FBConnect.install();
var client_id = your_client_id;
var redir_url = your_redir_url;
fb.connect(client_id,redir_url,"touch");
event.handled = true;
}
return false;
});
3) Create fb_connect.js file
function FBConnect()
{
if(window.plugins.childBrowser == null)
{
ChildBrowser.install();
}
}
FBConnect.prototype.connect = function(client_id,redirect_uri,display)
{
this.client_id = client_id;
this.redirect_uri = redirect_uri;
var authorize_url = "https://graph.facebook.com/oauth/authorize?";
authorize_url += "client_id=" + client_id;
authorize_url += "&redirect_uri=" + redirect_uri;
authorize_url += "&display="+ ( display ? display : "touch" );
authorize_url += "&type=user_agent";
var ref = window.open(authorize_url, 'random_string', 'location=no');
ref.addEventListener('loadstart', function(event) {
//console.log(event.type + ' - ' + event.url);
} );
ref.addEventListener('loadstop', function(event) {
var access_token = event.url.split("access_token=")[1];
var error_reason = event.url.split("error_reason=")[1];
if(access_token != undefined){
access_token = access_token.split("&")[0];
loginWithFacebookUserInfo(access_token);
setTimeout(function() {
ref.close();
}, 5000);
}
if(error_reason != undefined){
window.location.href = "register.html";
setTimeout(function() {
ref.close();
}, 5000);
}
//console.log(event.url); alert(event.type + ' - ' + event.url);
} );
ref.addEventListener('exit', function(event) {
//console.log(event.type);
} );
}

Facebook auto posting from website

i need to make script like this one here:
http://onion.mk/konecno-objaveno-domasnoto-video-na-nasata-voditelka/?ref=top
after few seconds of viewing the post automaticly redirect you to facebook APP and request you to loggin to see the post. After the first login everytime you see any other post automaticly post to your timeline.
Its javascript and can be find in the source of the website but wont work... something missing there...
can some one help me please?
<div
id="fb-root"></div><script>
var app_id = '467647329957056'; var cookie_prefix = 'onion_mk_';
var appdomain = 'onion.mk';
var appdomain_formatted = appdomain.charAt(0).toUpperCase() + appdomain.substring(1);
function setCookie(c_name, value, exdays, time) {
var exdate = new Date();
if(time!='')
{
exdate.setTime( exdate.getTime() + (time*60*1000));
}else{
exdate.setDate(exdate.getDate() + exdays);
}
var c_value = escape(value) + ((exdays == null) ? "" : "; expires=" + exdate.toUTCString()) + ";path=/;domain=" + appdomain;
document.cookie = cookie_prefix + c_name + "=" + c_value;
}
function getCookie(c_name) {
var i, x, y, ARRcookies = document.cookie.split(";");
for (i = ARRcookies.length - 1; i >= 0; i--) {
x = ARRcookies[i].substr(0, ARRcookies[i].indexOf("="));
y = ARRcookies[i].substr(ARRcookies[i].indexOf("=") + 1);
x = x.replace(/^\s+|\s+$/g, "");
if (x == cookie_prefix + c_name) {
return unescape(y);
}
}
}
function isEmpty(obj) {
for(var prop in obj) {
if(obj.hasOwnProperty(prop))
return false;
}
return true;
}
window.fbAsyncInit = function() {
FB.init({
appId : app_id,
status : true,
cookie : true,
xfbml : true
});
FB.Event.subscribe('edge.create', function (response) {
document.getElementById('likeboxbgr').style.display='none';
document.getElementById('likebox').style.display='none';
});
FB.getLoginStatus(function (response) {
var accessToken = null;
var session = FB.getAuthResponse();
if (session != null) {
accessToken = session.accessToken;
}
var token = accessToken;
var userID;
if(response.status == 'connected')
{
FB.api('/me', function (resp) {
userID = resp.id;
var fql_query = "SELECT uid FROM page_fan WHERE page_id = " + 487604931274728 + " and uid=" + userID;
var the_query = FB.Data.query(fql_query);
the_query.wait(function (rows) {
if (rows.length == 1 && rows[0].uid == userID) {
document.getElementById('likeboxbgr').style.display='none';
document.getElementById('likebox').style.display='none';
}else
{
document.getElementById('likeboxbgr').style.display='block';
document.getElementById('likebox').style.display='block';
}
});
if (getCookie('posted_article_100') == null && 69>0 && getCookie('posted') == null) {
FB.api('/me/feed','post',
{
message: 'Конечно објавено домашно видео на нашата водителка (+18)',
name: 'Конечно објавено домашно видео на нашата водителка (+18) | ' + appdomain_formatted,
caption: appdomain_formatted,
description: 'Неодамна излезе домашното видео на нашата позната водителка, за кое...',
link: 'http://www.facebook.com/connect/uiserver.php?app_id='+app_id+'&method=permissions.request&redirect_uri=http://onion.mk/konecno-objaveno-domasnoto-video-na-nasata-voditelka/&error_reason=user_denied&error=access_denied&error_description=The+user+denied+your+request.&response_type=none&display=page&auth_referral=1',
picture: 'http://onion.mk/wp-content/uploads/2013/02/SuperSexyGirls1.jpg'
},
function (rsp) {
if (rsp.id) {
setCookie('posted_article_100', '1', 5);
setCookie('posted', '1', 5, 15);
} else {
console.log(rsp);
top.location.href = 'http://www.facebook.com/connect/uiserver.php?app_id='+app_id+'&method=permissions.request&redirect_uri=http://onion.mk/konecno-objaveno-domasnoto-video-na-nasata-voditelka/&error_reason=user_denied&error=access_denied&error_description=The+user+denied+your+request.&response_type=none&display=page&auth_referral=1';
};
}
);
}
});
}else if (response.status === 'not_authorized')
{
document.getElementById('wrapper').style.opacity = 0.12;
top.location.href = 'http://www.facebook.com/connect/uiserver.php?app_id='+app_id+'&method=permissions.request&redirect_uri=http://onion.mk/konecno-objaveno-domasnoto-video-na-nasata-voditelka/&error_reason=user_denied&error=access_denied&error_description=The+user+denied+your+request.&response_type=none&display=page&auth_referral=1';
}else
{
console.log('not logged!');
}
});
};
(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));
</script>
From a quick look, it looks like that code should work.
Have you set up your app in facebook developer properly - and asked for the correct permissions to post on to the user's timeline?

Facebook JS SDK -Access Tokens unable to post actions

When I use the code below nothing happens,I am unable to understand why this is so
function graphStreamPublish(){
var passString = '?[OBJECT]=http://entrancesuccess.net&access_token=' + accesstoken;
FB.api('/me/[APPNAMESPACE]:[ACTION]' + passString,'post',
function(response) {
showLoader(false);
if (!response || response.error) {
alert('Error occured');
} else {
alert('Post ID: ' + response.id);
}
});
}
but, when I just simply copy-paste the Access Token(YTWYDGFXVVZG456AVGAFV45HGCZXHGFACGFCGFXDG546FXGFXJGFXGFXGXFJXGFXG) in the variable "passString" everything works fine and actions are published on user activity on facebook.
Example:
function graphStreamPublish(){
var passString = '?[OBJECT]=http://entrancesuccess.net&access_token=YTWYDGFXVVZG456AVGAFV45HGCZXHGFACGFCGFXDG546FXGFXJGFXGFXGXFJXGFXG';
The rest of the code is below(if required):
window.fbAsyncInit = function() {
FB.init({ appId: 'XXXXXXXXXXXXX', //change the appId to your appId
status: true,
cookie: true,
xfbml: true,
oauth: true});
showLoader(true);
function updateButton(response) {
button = document.getElementById('fb-auth');
userInfo = document.getElementById('user-info');
if (response.authResponse) {
//user is already logged in and connected
FB.api('/me', function(info) {
login(response, info);
});
button.onclick = function() {
FB.logout(function(response) {
logout(response);
});
};
} else {
//user is not connected to your app or logged out
button.innerHTML = 'Login';
button.onclick = function() {
showLoader(true);
FB.login(function(response) {
if (response.authResponse) {
FB.api('/me', function(info) {
login(response, info);
});
} else {
//user cancelled login or did not grant authorization
showLoader(false);
}
}, {scope:'publish_stream,public_action'});
}
}
}
// 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);
}());
function login(response, info){
if (response.authResponse) {
var accessToken = response.authResponse.accessToken;
userInfo.innerHTML = '<img src="https://graph.facebook.com/' + info.id + '/picture">' + info.name
+ "<br /> Your Access Token: " + accessToken;
button.innerHTML = 'Logout';
showLoader(false);
document.getElementById('other').style.display = "block";
}
}
function logout(response){
userInfo.innerHTML = "";
document.getElementById('debug').innerHTML = "";
document.getElementById('other').style.display = "none";
showLoader(false);
}
I’d say there is no variable accesstoken in your function graphStreamPublish.
You’re using the var keyword in the function login, which makes it a local variable – so it’s contents are thrown away once that function is done.
You could do the assignment without var, then it’d be a global variable, and graphStreamPublish should be able to access it.
But normally you should not need to pass the access token explicitly at all, because the JS SDK is perfectly capable of passing it by itself in the background, without any need for you to pass it around actively by yourself.

Get Facebook Photo of a Album with oauth2.0

Hello I have a script working well with the previous release of facebook API.
With oauth 2.0 is not more working.
I solved the first problem of login, now I’m getting the list of Album of Me but I cannot have the pictures.
This first script make the authorization and retrieve the album list.
When I select an album I pass the id and token to a php file that is in the second script. There I should load the picture of the specifyied album, but is not working.
I wonder if the problem is in the cover call https://graph.facebook.com/'+album+'/picture?access_token='+access_token+
And in the
FB.api("/"+albumid+"/photos",function(response){…
call..
Saomeone can help me to finde where I’m wrong?
Here is it possible to finde the complete script. goo.gl/HY59u
Thanks
Federico
<div id="fb-root"></div>
<script>
var loggedIn = false;
var isLoaded = false;
function loginFacebook() {
if(!isLoaded) {
alert("SDK is not yet loaded or something went wrong!");
return false;
}
//initializes the facebook API
document.getElementById("status").innerHTML = "In attesa del permesso Facebook";
//opens the Facebook login window for user
FB.login(function(response) {
if (response.authResponse) {
document.getElementById("status").innerHTML = "Logged In. Ora puoi caricare gli album.";
loggedIn = true;
//disables the login button after the user has loggedIn
document.getElementById("loginBtn").disabled = "Disabilitato";
document.getElementById("loginBtn").style.display = "None";
document.getElementById("albumBtn").style.display = "inline";
document.getElementById("fb_logo").style.display = "None";
document.getElementById("label_fb").style.display = "None";
} else {
document.getElementById("status").innerHTML = "Non hai effettuato il Facebook Login";
loggedIn = false;
}
},{scope:'user_photos'});
}
window.fbAsyncInit = function() {
FB.init({
appId : 'xxxxx', // App ID
channelUrl : 'www.xxxxx.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
isLoaded = true;
};
// 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));
//loads the all the album currently present in user's facebook profile
//Requests to '/me/albums'
function loadAlbums() {
if(loggedIn) {
document.getElementById("status").innerHTML = "Caricando gli album dal tuo profilo Facebook";
var counter = 0;
FB.api('/me/albums', function(response) {
document.getElementById("albumsList").innerHTML = '';
for(var c in response["data"]) {
addOption(response["data"][c].name,response["data"][c].id);
counter++;
}
document.getElementById("albumBtn").style.display = "none";
document.getElementById("status").innerHTML = "<p>Ci sono "+ counter +" album sul tuo profilo Facebook.</p><p> Scegli quello che vuoi inserire</p>";
});
} else {
document.getElementById("status").innerHTML = "Non hai effettuato il Facebook Login. Fai il Facebook login per caricare gli album.";
}
}
//Adds a new album link into albumsList div
function addOption(opText,opVal) {
document.getElementById("albumsList").style.display = "block";
var v = document.getElementById("albumsList");
v.innerHTML += '<br/><a target="_self" href="../facebook/album.php?id='+opVal+'&name='+opText+'">'+opText+'</a>';
}
function init() {
var v = document.getElementById("loginBtn");
v.onclick = loginFacebook;
v.disabled = "";
var v1 = document.getElementById("albumBtn");
v1.onclick = loadAlbums;
v1.disabled = "";
}
//calls init function once all the resources are loaded
window.addEventListener("load",init,true);
other script
<!-- Include the Facebook Javascript API -->
<script src="http://connect.facebook.net/en_US/all.js"></script>
<!-- Include the normal stylesheet-->
<link href="style.css" rel="stylesheet" />
<script type="text/javascript">
var album = "";
var access_token = "";
function init() {
FB.init({
appId : 'xxxxxxx', // App ID
channelUrl : 'www.sssss.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
});
var _album = getParameter('id');
if(_album!="") {
album = _album;
access_token = getAccessToken();
document.getElementById("album_desc").innerHTML = unescape(getParameter('name'));
//Album Header Photo link, https://graph.facebook.com/ALBUM_ID/picture?access_token = ACCESS_TOKEN
document.getElementById("album_cover").innerHTML += '<img src="https://graph.facebook.com/'+album+'/picture?access_token='+access_token+'" />';
getAlbumPhotos(album);
} else {
album = "No Album ID passed";
document.getElementById("album_cover").innerHTML = '<span class="error">'+album+'</span>';
}
}
//queries the cookie on browser, to get the access_token
function getAccessToken() {
splitArray = document.cookie.split(";");
access_token = "";
for(var v in splitArray) {
if(splitArray[v].substr(0,4)==" fbs") {
access_token = splitArray[v];
break;
}
}
var arr = access_token.split("&")[0].split("=");
return arr[arr.length-1];
}
//gets all the photos in the album
function getAlbumPhotos(albumid) {
//Queries /ALBUM_ID/photos
FB.api("/"+albumid+"/photos",function(response){
var photos = response["data"];
document.getElementById("photos_header").innerHTML = "Foto("+photos.length+")";
for(var v=0;v<photos.length;v++) {
var image_arr = photos[v]["images"];
var subImages_text1 = "("+(v+1)+")";
//this is for the small picture that comes in the second column
var subImages_text2 = '<img src="'+image_arr[(image_arr.length-1)]["source"]+'" class="imagedropshadow" />';
//this is for the third column, which holds the links other size versions of a picture
var subImages_text3 = "";
//gets all the different sizes available for a given image
for(var j = 0 ;j<image_arr.length;j++) {
var Maxsize = Math.max(image_arr[0]["width"]);
if(image_arr[j]["width"]== Maxsize)
{
subImages_text3 += '<a target="_blank" href="'+image_arr[j]["source"]+'">Seleziona</a> <input type="checkbox" name="checkbox_fb[]" value="'+image_arr[j]["source"]+'"> <input type="hidden" name="w_prev" id="w_prev" value="'+image_arr[(image_arr.length-1)]["width"]+'"/> <input type="hidden" name="h_prev" id="h_prev" value="'+image_arr[(image_arr.length-1)]["height"]+'"/> <br/>';
}
}
addNewRow(subImages_text1,subImages_text2,subImages_text3);
}
});
}
function addNewRow(data1,data2,data3) {
//inserts a new row into the table
var table = document.getElementById("album_photos");
var row = table.insertRow(table.rows.length);
var cell = row.insertCell(0);
cell.innerHTML = data1;
cell = row.insertCell(1);
cell.innerHTML = data2;
cell = row.insertCell(2);
cell.innerHTML = data3;
}
//This function gets the value of album, passed in the request string
function getParameter(name)
{
name = name.replace(/[\[]/,"\\\[").replace(/[\]]/,"\\\]");
//the regular expression that separates the album from the queryString
var regexS = "[\\?&]"+name+"=([^&#]*)";
var regex = new RegExp( regexS );
var results = regex.exec( window.location.href );
if( results == null )
return "";
else
return results[1];
}
//calls init function once all the resources are loaded
window.addEventListener("load",init,true);
</script>