I'm using the login code from Facebooks documentation:
This works fine in desktop browsers but on tablets the whole site tries to redirect to an https://m.facebook.com... URL instead of showing the permissions pop up. The page it redirects to just displays Error. Can pop ups not work in Facebook Javascript SDK?
<div id="fb-root"></div>
<script type="text/javascript">
var likesPage = false;
var addisPageId = 'XXXXXX';
window.fbAsyncInit = function () {
// init the FB JS SDK
FB.init({
appId: 'XXXXXXX', // App ID from the app dashboard
channelUrl: '/channel.html', // Channel file for x-domain comms
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
};
// 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_gb/all.js";
fjs.parentNode.insertBefore(js, fjs);
} (document, 'script', 'facebook-jssdk'));
function callLogin() {
FB.login(function (response) {
var access_token = FB.getAuthResponse()['accessToken'];
$("#at").val(access_token);
if (response.authResponse) {
FB.api('/me/likes?fields=id', function (response) {
for (var i = 0; i < response.data.length; i++) {
if (response.data[i].id == addisPageId) {
likesPage = true;
break;
}
}
if (likesPage) {
FB.api('/me', function (userInfo) {
document.getElementById("email").value = userInfo.email;
document.getElementById("fbId").value = userInfo.id;
document.getElementById("fbform").submit();
});
} else {
document.getElementById("dontLikePage").style.display = "inline";
}
});
} else {
window.parent.location = "https://www.facebook.com/XXXX";
}
}, { scope: 'user_likes,email,publish_stream' });
}
</script>
Had this issue a while a go. I got around it by using thee facebook login button https://developers.facebook.com/docs/reference/plugins/login/ this works fine on tablets but using the fb.login in javascript just errors because of the issue you described.
Related
I have integrated Facebook Page plugin in my Vuejs app. When I move from one component to another and return back to the component containing the Facebook Page, the page aint loading. It is loading only for the first time and every time I load the complete site. Any solution ?
Found the answer after some digging.
I needed to explicitly load the script every time the component was mounted.
Used this NPM package [ https://www.npmjs.com/package/vue-plugin-load-script ]
mounted() {
this.$loadScript(
"https://connect.facebook.net/en_GB/sdk.js#xfbml=1&version=v5.0&appId=***&autoLogAppEvents=1"
)
.then(() => {
this.$nextTick(() => {
window.FB.XFBML.parse();
});
})
.catch(() => {
console.log("SCRIPT LAODING ERROR");
});
}
You can get FB to parse with vue router like this:
mounted() {
if (typeof FB === "undefined") {
this.fbInit();
} else {
window.FB.XFBML.parse();
}
}
methods() {
fbInit() {
window.fbAsyncInit = function() {
FB.init({
appId: "11111111111",
autoLogAppEvents: true,
xfbml: true,
version: "v6.0"
});
FB.AppEvents.logPageView();
};
(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/fi_FI/sdk.js";
fjs.parentNode.insertBefore(js, fjs);
})(document, "script", "facebook-jssdk");
},
}
i'm using flask, and this is the code on the back end, copied from a source listed on flask-dance documentation:
app.config["FACEBOOK_OAUTH_CLIENT_ID"] = os.environ.get("xxxxxxx")
app.config["FACEBOOK_OAUTH_CLIENT_SECRET"] = os.environ.get("yyyyyy")
facebook_bp = make_facebook_blueprint()
app.register_blueprint(facebook_bp, url_prefix="/login")
#app.route("/")
def index():
if not facebook.authorized:
return redirect(url_for("facebook.login"))
resp = facebook.get("/me")
assert resp.ok, resp.text
return "You are {name} on Facebook".format(name=resp.json()["name"])
on the front end, i have this, provided by facebook itself:
window.fbAsyncInit =
function()
{
FB.init
(
{
//Generate through Facebook developer page
appId:"xxxxxxx",
cookie: true,
xfbml: true,
version: "v4.0"
}
);
getLoginStatus();
}
function getLoginStatus()
{
FB.getLoginStatus(function(res){
if( res.status == "connected" ){
FB.api('/me', {fields: 'first_name,last_name,name,id,picture.width(150).height(150)'}, function(fbUser) {
// console.log(fbUser.name);
var id = fbUser.id;
var name = fbUser.name;
date = new Date().toLocaleString();
var my_data = {name:name,id:id,date:date,language:language};
$.ajax({url: "/fb",data: my_data,type: 'POST',
success: function(response) {
console.log(response);
},
error: function(error) {
console.log(error)
console.log('error in fb');
}})
});
}
});
}
function checkLoginState()
{
getLoginStatus();
}
(
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/sdk.js";
fjs.parentNode.insertBefore(js, fjs);
}
)(document, "script", "facebook-jssdk");
i'm 100% sure both the app id and app secret are correct (just copied and pasted it). i checked another stackoverflow topic on this issue and people were suggesting the OP to make sure he wasn't on sandbox mode. i never even heard of it, but i did try switching to debug=False.
I'm using FB Client Api for Oauth authentication
All necessary data after login is recieved while authentication dialog becomes blank and doesn't close after successfull authentication. This behavior is only specific for IE 11. The rest of browsers close Oauth dialog successfully.
Here is init code for FB SDK:
(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/sdk.js";
fjs.parentNode.insertBefore(js, fjs);
}(document, 'script', 'facebook-jssdk'));
},
This is my init code for FB Login
function fbAsyncInit() {
FB.init({
appId: options.applicationId, // App ID
status : true,
xfbml : true
});
FB.getLoginStatus( callback );
}
window.fbAsyncInit = window.fbAsyncInit || fbAsyncInit;
And the last but not least: authorization function
authorize = function() {
var dfd = new $.Deferred();
FB.Event.subscribe( "auth.authResponseChange", function( response ) {
if ( response.status === "connected" ) {
dfd.resolve();
return;
} else {
FB.login(function() {
dfd.resolve();
});
}
});
FB.getLoginStatus(function( response ) {
if ( response && response.status === "connected" ) {
dfd.resolve();
return;
}
FB.login();
});
return dfd.promise();
};
Once again - I recieve all necessary events, problem is that dialog doesn't close after successfull authentication.
I have created a Facebook app which will share a link to users wall
but the issue is the link is posted on my wall but not on any other user's wall
i have put on live link Link to post on wall app
the code of app that will post on users wall is given below is there anything i need to approve it from the facebook or is there any mistake in my code please i need a real help any one could do ?
waiting for your kind response i am new to the Facebook API
<div id="fb-root"></div>
<script>
window.fbAsyncInit = function() {
// init the FB JS SDK
FB.init({
appId: '763390233734216', // App ID from the app dashboard
//channelUrl : '//local.facebook-test/channel.html', // Channel file for x-domain comms
status: true, // Check Facebook Login status
xfbml: true, // Look for social plugins on the page
oauth: true // Enable oauth authentication
});
// Additional initialization code such as adding Event Listeners goes here
FB.login(function(response) {
if (response.authResponse) {
console.log(response.authResponse.accessToken);
var params = {};
params['name'] = 'Seasons Canola';
params['description'] = 'Description';
params['link'] = 'http://vimeo.com/99708842';
FB.api('/me/feed', 'post', params, function(response) {
if (!response || response.error) {
alert('Error occured');
} else {
alert('Post ID: ' + response.id);
}
});
} else {
alert('Not logged in');
}
}, {
scope: 'public_profile,email,publish_actions'
});
};
// 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>
I need to get the access token from FB.login method in Javascript SDK. My login code is
FB.login(function(response) {
if (response.session) {
if (response.perms) {
} else {
// user is logged in, but did not grant any permissions
alert("No Permission..");
}
} else {
// user is not logged in
alert("Please login to facebook");
}
}, {perms:'read_stream,publish_stream,offline_access'});
Is there any way to get access token? I am able to get the access token using PHP.
You can get access token using FB.getAuthResponse()['accessToken']:
FB.login(function(response) {
if (response.authResponse) {
var access_token = FB.getAuthResponse()['accessToken'];
console.log('Access Token = '+ access_token);
FB.api('/me', function(response) {
console.log('Good to see you, ' + response.name + '.');
});
} else {
console.log('User cancelled login or did not fully authorize.');
}
}, {scope: ''});
Edit:
Updated to use Oauth 2.0, required since December 2011. Now uses FB.getAuthResponse();
If you are using a browser that does not have a console, (I'm talking to you, Internet Explorer) be sure to comment out the console.log lines or use a log-failsafe script such as:
if (typeof(console) == "undefined") { console = {}; }
if (typeof(console.log) == "undefined") { console.log = function() { return 0; } }
response.session.access_token doesn't work in my code. But this works:
response.authResponse.accessToken
FB.login(function(response) { alert(response.authResponse.accessToken);
}, {perms:'read_stream,publish_stream,offline_access'});
If you are already connected, simply type this in the javascript console:
FB.getAuthResponse()['accessToken']
https://developers.facebook.com/docs/facebook-login/login-flow-for-web/
{
status: 'connected',
authResponse: {
accessToken: '...',
expiresIn:'...',
signedRequest:'...',
userID:'...'
}
}
FB.login(function(response) {
if (response.authResponse) {
// The person logged into your app
} else {
// The person cancelled the login dialog
}
});
response.session doesn't work anymore because response.authResponse is the new way to access the response content after the oauth migration.Check this for details:
SDKs & Tools › JavaScript SDK › FB.login
window.fbAsyncInit = function () {
FB.init({
appId: 'Your-appId',
cookie: false, // enable cookies to allow the server to access
// the session
xfbml: true, // parse social plugins on this page
version: 'v2.0' // use version 2.0
});
};
// 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'));
function fb_login() {
FB.login(function (response) {
if (response.authResponse) {
console.log('Welcome! Fetching your information.... ');
//console.log(response); // dump complete info
access_token = response.authResponse.accessToken; //get access token
user_id = response.authResponse.userID; //get FB UID
FB.api('/me', function (response) {
var email = response.email;
var name = response.name;
window.location = 'http://localhost:12962/Account/FacebookLogin/' + email + '/' + name;
// used in my mvc3 controller for //AuthenticationFormsAuthentication.SetAuthCookie(email, true);
});
} else {
//user hit cancel button
console.log('User cancelled login or did not fully authorize.');
}
}, {
scope: 'email'
});
}
<!-- custom image -->
<img src="/Public/assets/images/facebook/facebook_connect_button.png" />
<!-- Facebook button -->
<fb:login-button scope="public_profile,email" onlogin="fb_login();">
</fb:login-button>
window.fbAsyncInit = function () {
FB.init({
appId: 'Your-appId',
cookie: false, // enable cookies to allow the server to access
// the session
xfbml: true, // parse social plugins on this page
version: 'v2.0' // use version 2.0
});
};
// 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'));
function fb_login() {
FB.login(function (response) {
if (response.authResponse) {
console.log('Welcome! Fetching your information.... ');
//console.log(response); // dump complete info
access_token = response.authResponse.accessToken; //get access token
user_id = response.authResponse.userID; //get FB UID
FB.api('/me', function (response) {
var email = response.email;
var name = response.name;
window.location = 'http://localhost:12962/Account/FacebookLogin/' + email + '/' + name;
// used in my mvc3 controller for //AuthenticationFormsAuthentication.SetAuthCookie(email, true);
});
} else {
//user hit cancel button
console.log('User cancelled login or did not fully authorize.');
}
}, {
scope: 'email'
});
}
<!-- custom image -->
<img src="/Public/assets/images/facebook/facebook_connect_button.png" />
<!-- Facebook button -->
<fb:login-button scope="public_profile,email" onlogin="fb_login();">
</fb:login-button>