Facebook javascript events not fired any way i turn it - javascript

I am using Facebook JavaScript SDK with my site, there is an option there to set events when user login/logout from Facebook so i can show him notifications in my website.
can't manage it to work, tried everything, also using offline_access permission.
here is my html code:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xmlns:og="http://ogp.me/ns#" xmlns:fb="http://www.facebook.com/2008/fbml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<meta name="description" content="blabla" />
<meta name="keywords" content="blabla" />
<meta property="og:title" content="blabla" />
<meta property="og:url" content="http://XXX/" />
<meta property="fb:app_id" content="XXX" />
<title>Facebook Notifier</title>
<link href="<?php echo base_url(); ?>styles/style.css" rel="stylesheet" type="text/css" />
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.6.4/jquery.min.js"></script>
<script type="text/javascript" src="<?php echo base_url(); ?>js/jquery.cookie.js"></script>
<script src="http://connect.facebook.net/en_US/all.js"></script>
<script type="text/javascript" src="<?php echo base_url(); ?>js/global.js"></script>
</head>
<body>
<div id="fb-root"></div>
<div id="my_div">
</div>
</a>
</body></html>
here is my js code:
FB.init({
appId : 'XXX',
status : true, // check login status
cookie : true, // enable cookies to allow the server to access the session
xfbml : true, // parse XFBML
oauth : true, // enables OAuth 2.0
channelUrl : 'http://XXX/channelUrl'
});
FB.getLoginStatus(function(response) {
if (response.authResponse) {
connected = true;
}
else{
connected = false;
}
}, true);
FB.Event.subscribe('auth.authResponseChange', function(response) {
if(response.authResponse) connected = true;
else connected = false;
});
in the end of this js code i have a function that run every few seconds checking the connection variable, its a global one. and it not changed i tried to login/logout from facebook and no event fires.
only when i refresh the page i can get the user status.
in firefox firebug console i get the message (also tried in chrome, ie):
uncaught exception: Error: https://www.facebook.com Proxy.InstallTrigger
i tried to solve it by doing everything i can find about this error in google and also in stackoverflow and still not working.
btw: when i wrote XXX in the original files its my url or my appid.
thanks.

I've always been a bit skeptical about the auth. events the Facebook fires so in your case I'd prob just setup a poller myself to check the auth status of the connected users. Like this:
var connected;
FB.init({
appId : 'XXX',
status : true, // check login status
cookie : true, // enable cookies to allow the server to access the session
xfbml : true, // parse XFBML
oauth : true, // enables OAuth 2.0
channelUrl : 'http://XXX/channelUrl'
});
FB.getLoginStatus(handleUserStateChange);
FB.Event.subscribe('auth.authResponseChange', handleUserStateChange);
function handleUserStateChange(response) {
connected = !!response.authResponse;
}
setInterval(function() {
FB.getLoginStatus(handleUserStateChange, true);
}, 10000) // poll every 10 seconds
Also as you defined status: true in the FB.init config object you don't need to pass the second parameter to FB.getLoginStatus at the start as that forces a check to Facebook instead of reading from the stored variable (which is already the latest information as we just initd).

It looks like you might have a variable scope problem with connected.
Something like this might help:
var connected; // define/initialize connected variable outside functions
FB.init({
appId : 'XXX',
status : true, // check login status
cookie : true, // enable cookies to allow the server to access the session
xfbml : true, // parse XFBML
oauth : true, // enables OAuth 2.0
channelUrl : 'http://XXX/channelUrl'
});
FB.getLoginStatus(function(response) {
if (response.authResponse) {
connected = true;
}
else{
connected = false;
}
}, true);
FB.Event.subscribe('auth.authResponseChange', function(response) {
if(response.authResponse) connected = true;
else connected = false;
});
I would use console.log() from within your functions that respond to subscribed events to see what is really happening (or not happening). Then write your real code based on what console.log() tells you.

I am doing FB.Event.subscribe in a function that is invoked on document ready event:
<script>(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#xfbml=1&appId=...";
fjs.parentNode.insertBefore(js, fjs);
}(document, 'script', 'facebook-jssdk'));
$("document").ready(function(){
FB.Event.subscribe('edge.create',
function(response) {
alert('You liked the URL: ' + response);
});
});
</script>
Or here there is another example of making sure that FB is initialised before you do any invocations.

I'm all new into FB development and ran into the same issue a couple days ago.
I tried pretty much all answers and solutions that are out there but nothing
worked out. The damn event wouldn't want to fire no matter what I did in my
latest VS project. However I remembered getting this to work in my first VS project
where I followed a tutorial on the same matter. After a while I checked that initial project and to my surprise it fired there and not in my other one.
Finally I realized that the Canvas Url on FB (app settings) was the culprit :
h t t p: // localhost:15497/
It was set to my localhost with the port used in my other project. I changed the port number and suddenly it also worked in my other project.
Make sure that the canvas url in the FB app settings matches where your Visual Studio runs the app. Also change the value once you deploy your web app.

If you're in 2022 wondering why it won't fire. Enable 3rd party cookies, this worked for me.

Related

How to use Facebook test app to do Facebook Login - Web JavaScript

This is my first time to write JavaScript.... I am using JSBin as the IDE. And I am trying to use JavaScript to allow users login and get their public data in Facebook Graph API.
I created a Facebook Web App, and then created a Test App for this App. None of these 2 Apps work. For each of these Apps, I have created a test user like this:
Below Are How I Failed....
First Try:
I have checked this Facebook Login Doc, changed the app id to my own app id, and version changed to 2.6 as my app settings. But, the problem is, on JSBin, nothing show up.....
Second Try:
Then I found an online example, and I modified the code to make it like this
<html>
<body>
<div id="fb-root"></div>
<script>
window.fbAsyncInit = function() {
FB.init({
appId : '1814637902090044',
cookie : true,
xfbml : true, // parse social plugins on this page
version : 'v2.6' // use graph api version 2.6
});
FB.Event.subscribe('auth.authResponseChange', function(response)
{
if (response.status === 'connected')
{
document.getElementById("message").innerHTML += "<br>Connected to Facebook";
}
else if (response.status === 'not_authorized')
{
document.getElementById("message").innerHTML += "<br>Failed to Connect";
} else
{
document.getElementById("message").innerHTML += "<br>Logged Out";
}
});
};
function Login()
{
FB.login(function(response) {
if (response.authResponse)
{
getUserInfo();
} else
{
console.log('User cancelled login or did not fully authorize.');
}
},{scope: 'email'});
}
function getUserInfo() {
FB.api('/100012237662406', function(response) {
var str = "<b>Email:</b> "+response.email+"<br>";
document.getElementById("status").innerHTML=str;
});
}
// 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>
<div align="center">
<h2>Facebook OAuth Javascript Demo</h2>
<div id="status">
Click on Below Image to start the demo: <br/>
<img src="http://hayageek.com/examples/oauth/facebook/oauth- javascript/LoginWithFacebook.png" style="cursor:pointer;" onclick="Login()"/>
</div><div id="message">Logs:<br/>
</div></div>
</body>
As you can see, I am using the app id of my Test App, the user is my test user id, but when I click the button, always get this error
Third Try:
Since above error shows "app in development mode....", I have checked these 2 solutions: Solution 1, Solution 2. But I really cannot find those choices in App Review and I cannot find Status & Review. When it comes to Test App, it even has no App Review. Then I tried to public my App like this
But then I got the error:
Here are the url settings:
For that Redirect URL, I have also tried http://localhost/oauthcallback.html, but didn't work either. I don't have any real url can be used for redirect....
I think, if Test App without App Review can be used to test Facebook Login, it may not be the settings in App Review problems.
Do you know how to solve this problem, so that my Javascript will allow user login and send me their public data in Graph API?

PHP & Javascript Asynchronous permissions Authentication - Facebook API's

What would I need to do to allow asynchronous login/authentication (permissions) between an external site for mobiles and a facebook tab app.
I essentially need one system that does both desktop/mobile.
Example
Case 1 (Mobile/external access) - Logs in using Javascript using login and works fine app works perfectly. - This works the way it's supposed to which is great!
case 2(Facebook user - tab app) - Logs in and gains permissions through PHP SDK onviously the user is already logged in. My problem is javascript knows the user is logged in but still asks the user to login for the permissions they've already given.
TLDR: Why won't Javascript pickup the Auth cookie from the PHP SDK and recognise the user has the correct permissions from PHP? This login flow is fine when the user has logged in via mobile or externally to the app. I've tried them seperately and they work fine just won't work together.
I've seen it working the other way around but I want JS only or PHP>JS NOT JS>PHP.
*Edit
window.fbAsyncInit = function()
{
FB.init({
appId : 'APP_ID_HERE', // 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
oauth : true // enable OAuth 2.0
});
my event handlers for login/logout and likes goes here.
(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 fblogin()
{
FB.login(function(response)
{
},
{ scope: 'email, user_likes' }
);
}
function createRequestObject() {
var obj;
var browser = navigator.appName;
if(browser == "Microsoft Internet Explorer")
{
obj = new ActiveXObject("Microsoft.XMLHTTP");
}
else
{
obj = new XMLHttpRequest();
}
return obj;
}
Login for mobile/desktop works great it's picking up the scope but when I use the following code to setup the tab app, the permissions won't transfer to the javascript session.
PHP Code (which works):
<?php
require_once 'src/facebook.php'; // get facebook sdk
$facebook = new Facebook(array(
'appId' => 'APP ID HERE',
'secret' => 'APP SECRET HERE'
));
$user = $facebook->getUser();
$location = "". $facebook->getLoginUrl(array('scope' => 'email, user_likes'));
// check if we have valid user
if ($user) {
try {
// Proceed knowing you have a logged in user who's authenticated.
$permissions = $facebook->api('/me/permissions', 'get', array('access_token'=>$access_token));
} catch (FacebookApiException $e) {
$fb_user_id = NULL;
// seems we don't have enough permissions
// we use javascript to redirect user instead of header() due to Facebook bug
print '<script language="javascript" type="text/javascript"> top.location.href="' . $location .'"; </script>';
// kill the code so nothing else will happen before user gives us permissions
echo $e->getMessage();
die();
}
} else {
// seems our user hasn't logged in, redirect user to a FB login page
print '<script language="javascript" type="text/javascript"> top.location.href="'. $location .'"; </script>';
// kill the code so nothing else will happen before user gives us permissions
die();
}
// at this point we have an logged in user who has given permissions to our APP
// Facebook opens canvas page (which is the mobile/external page) but doesn't transfer permissions.
PHP works great it transfers the user to the mobile (canvas) page with login/like button. How do I get PHP to pass the perms to my canvas where my mobile/desktop site is?
*EDIT 2:
HTML/PHP:
<div class="container">
<div id="fb-root"></div>
<div id="facebook-div">
<fb:login-button autologoutlink="true" scope="email,user_likes" size="large"></fb:login-button>
<div id="facebook-right" class="fb-like" data-href="https://www.facebook.com/154456204613952" data-width="90" data-layout="button_count" data-show-faces="false" data-send="false"></div>
</div>
//Rest of the code here
Managed to resolve it thanks for your help!
After the PHP instantiated I didn't include the Canvas php file after the user was authenticated... I've been pulling my hair out for months trying to resolve this! This authentication gets passed to Javascript which deals with everything!
This means that both PHP and Javascript calls are able to work within the same application.

FB.api('/me/friends') throws error in Internet Explorer

I'm not sure its something I did wrong, (everything seems to go wrong in ie with the facebook sdk)
When I get the facebook friends FB.api('/me/friends' (already logged in), I got a weird error, "enable to get the property list"
On ie8 & ie9, it works on chrome and FF, anyone got a workaround?
I assume you use JavaScript and FBML because you tagged JavaScript and FBML
Here are the reasons of getting error in ie
Verify that you did place the below code correctly as I think you didn't.
1. Include the JavaScript SDK on your page once, ideally right after the opening <body> tag.
The following code will load and initialize the JavaScript SDK with all common options. Replace YOUR_APP_ID and WWW.YOUR_DOMAIN.COM with the appropriate values. The best place to put this code is right after the opening <body> tag.
<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'; 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>
2. Add an XML namespace to the <html> tag of your document. This is necessary for XFBML to work in earlier versions of Internet Explorer.
<html xmlns:fb="http://ogp.me/ns/fb#">
Thanks

FB.api is not a function

I'm trying to pull all of the posts on a users wall. I got an example running that connects to FB okay, but when I try to use FB.api to get the username (I am definitely successfully connected), I get FB.api is not a function. Some searching found this which suggests that I'm using the wrong API link, but when I try the new one (which seems to connect using the same method) everything firebug NET panel says it loads successfully, there are no errors. . . nothing happens at all.
Here is the code (replace the http://connect.facebook.net/en_US/all.js link with http://static.ak.connect.facebook.com/js/api_lib/v0.4/FeatureLoader.js.php for the code to work up until the error I mentioned):
<html xmlns="http://www.w3.org/1999/xhtml" xmlns:fb="http://www.facebook.com/2008/fbml">
<head>
<script src="http://connect.facebook.net/en_US/all.js" type="text/javascript"></script>
<script type="text/javascript">
function grab(){
FB.api('/me', function(response) {
alert(response.name);
});
}
function update_user_box() {
var user_box = document.getElementById("user");
user_box.innerHTML =
"<div>"
+ "<fb:profile-pic uid='loggedinuser' facebook-logo='true'></fb:profile-pic>"
+ " Welcome, <fb:name uid='loggedinuser' useyou='false'></fb:name>"
+ "</div>"
+ "try me";
FB.XFBML.Host.parseDomTree();
}
</script>
</head>
<body>
<div id='user'><fb:login-button onlogin="update_user_box();"></fb:login-button></div>
<br><br>
<div id="fb-root"></div>
<script type="text/javascript">
FB.init("b07e858317c9069d450023b7500b4511", "xd_receiver.htm", {"ifUserConnected": update_user_box});
</script>
</body>
</html>
thanks for any and all help!
You're using methods from two different SDKs. FB.api is part of the new SDK (all.js), and FB.XFBML.Host.parseDomTree() is part of the old SDK (feature loader). For example, to parse the dom tree with the new SDK, you call FB.XFBML.parse(). I recommend you pick one of the two SDKs, preferably the new SDK if you are just starting since the old SDK is deprecated.
I guess you are not intializing correctly. I had similar issues... it was not clear to me which one is oAuth2.0 and which FB-Connect. It seemed confusing. I followed the example (below), it worked for me. See here
<div id="fb-root"></div>
<script src="http://connect.facebook.net/en_US/all.js"></script>
<script>
FB.init({
appId : 'YOUR APP ID',
status : true, // check login status
cookie : true, // enable cookies to allow the server to access the session
xfbml : true // parse XFBML
});
</script>
Hope this helps.
On a side note, you might need extended permission to access publish_stream, read_stream. You should refer here
Typeoneerror is right, you're mixing SDK's.
Here's how I'm initializing the newer JS SDK, using event.subscribe to be sure the SDK is initialized AND the user has authenticated on the JS side before moving forward with any API calls or letting my game try to load etc.
<div id="fb-root"> </div>
<script>
window.fbAsyncInit = function() {
FB.init({appId: 'YOUR_APP_ID', status: true, cookie: true, xfbml: true});
FB.Canvas.setSize({ width: 760, height: 1000 }); // use this to increase canvas height
FB.Event.subscribe('auth.login', function(response) {
// You can call your function that requires FB.whatever here...
});
};
(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>
I'm also using the PHP SDK to perform the initial auth... If the user is not authed, I echo a JS redirect to our the login url (available from the PHP SDK method getLoginUrl). Hope that helps.

API Key Error in Facebook Connect (javascript sdk)

I am trying to implement Facebook Connect on a website. I am trying to work with Javascript SDK of Facebok. I am new to it and unfortunately most of links provided in Facebook WIKI are out of date... Returning 404 not found. Anyway I added this code before the ending </body>:
<script src="http://static.ak.fbcdn.net/connect.php/js/FB.Share" type="text/javascript"></script>
<div id="fb-root"></div>
<script src="http://static.ak.connect.facebook.com/js/api_lib/v0.4/FeatureLoader.js.php" type="text/javascript"> </script>
<script src="http://connect.facebook.net/en_US/all.js"></script>
<script>
FB.init({
appId : '12344', // my real app id is here
status : true, // check login status
cookie : true, // enable cookies to allow the server to access the session
xfbml : false // parse XFBML
});
FB.login(function(response) {
if (response.session) {
if (response.perms) {
alert('user is logged in and granted some permissions');
// user is logged in and granted some permissions.
// perms is a comma separated list of granted permissions
} else {
alert('user is logged in, but did not grant any permissions');
// user is logged in, but did not grant any permissions
}
} else {
alert('user is not logged in');
// user is not logged in
}
}, {perms:'email'});
</script>
And I have a login button at some other place (much before the above scripts) in the same page rendered with:
<fb:login-button v="2">Connect with Facebook</fb:login-button>
This button renders as a normal fb connect button and clicking it opens a new popup window as it normally should. Problem is that it shows 'invalid api key specified' error. On inspecting address bar of popup, I see that api_key=undefined is passed to it :(
Any idea about this? I am trying to fix this for last 5 hours now... Please help me found out why correct API key is not being passed to popup window.
Thanks in advance.
I'm doing the same thing, and i found an example that is very simple to implement and understand (here thay use jQuery, but you can do the same without libraries):
<body>
<div>
<button id="login">Login</button>
<button id="disconnect">Disconnect</button>
</div>
<div id="user-info" style="display: none;"></div>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js"></script>
<div id="fb-root"></div>
<script src="http://connect.facebook.net/en_US/all.js"></script>
<script>
// initialize the library with the API key
FB.init({ appId : '12344' });
// fetch the status on load
FB.getLoginStatus(handleSessionResponse);
$('#login').bind('click', function() {
FB.login(handleSessionResponse);
});
$('#disconnect').bind('click', function() {
FB.api({ method: 'Auth.revokeAuthorization' }, function(response) {
clearDisplay();
});
});
// no user, clear display
function clearDisplay() {
$('#user-info').hide('fast');
}
// handle a session response from any of the auth related calls
function handleSessionResponse(response) {
// if we dont have a session, just hide the user info
if (!response.session) {
clearDisplay();
return;
}
// if we have a session, query for the user's profile picture and name
FB.api(
{
method: 'fql.query',
query: 'SELECT name, pic FROM profile WHERE id=' + FB.getSession().uid
},
function(response) {
var user = response[0];
$('#user-info').html('<img src="' + user.pic + '">' + user.name).show('fast');
}
);
}
</script>
</body>
Look here for the entire code, and here you can find other resource.
I had set my facebook connect address to have www and I was accessing my test site with non www, when I switched to the www version fb connect worked fine.
You need to set the canvas post-authorize url, and make sure that the base canvas url is a prefix of the post-authorize url.

Categories

Resources