Facebook JavaScript API - Login failure in Chrome - javascript

The below code is from the official Facebook developer pages, and works in FF and Safari, and sometimes in Chrome — but more often not in Chrome.
On Snow Leopard with the latest Chrome, I click the login button and see a little flicker as the FB login dialog opens and closes. If, in my FB account, I remove and re-add the app, I get asked for permissions, but the auth.authResponseChange event never seems to fire.
Does anyone know if this is a bug, or where I might find a solution that doesn't require me to manually poll the server?
Is this a product of Google+ vs. Facebook?!
<html>
<head></head>
<body>
<div id="fb-root"></div>
<script>
window.fbAsyncInit = function() {
FB.init({
appId : $APP_ID$, // App ID from the app dashboard
channelUrl : $channelUrl$, // Channel file for x-domain comms
status : true, // Check Facebook Login status
cookie : true,
oauth : true,
xfbml : true // Look for social plugins on the page
});
// 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) {
console.log('auth.authResponseChange fired');
// 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.
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.
Learn more about options for the login button plugin:
/docs/reference/plugins/login/ -->
<!-- scope='publish_stream,read_stream' -->
<fb:login-button show-faces="true" width="200" max-rows="1"></fb:login-button>
</body>
</html>

Go into chrome settings - advanced settings; Under privacy click "content settings". See if the "Block 3rd party cookies and site data" is checked.
I'm having a similar issue where in chrome the js-sdk will give me the momentary fb popup, but doesnt actually seem to log the user in or recognize the user being logged in/authorized. In my case I think I've narrowed my issue down to that setting.
If you have it enabled, try disabling it to see if that fixes it for you... although that's really just a diagnostic step, it's not a resolution since you would still have users who have that setting enabled.
I'm trying to determine the workaround if any.. possibly involving the use of fb login flow "for web" (ie not using their sdk and thereby potentially avoiding the use of 3rd-party cookies)
here's my post on my version of this issue... can facebook javascript/php SDK's "talk" to each other if 3rd-party cookies are disabled? facebook->getUser() returns 0

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?

Firefox blocking Facebook Js

with upgrade of Firefox to 42.0 I got some strange behavior..
I'm calling FB.init method like this:
FB.init({
appId: '{$appid}',
status: true,
cookie: true,
xfbml: true,
oauth: true
});
But in Firefox it gets blocked, I get warning:
The resource at "https://connect.facebook.net/en_US/all.js" was blocked because tracking protection is enabled.
This is default behavior, I didn't set up any additional security or whatever..
What to do?
EDIT - after help and googling, this is a little bigger problem:
Turns out Firefox's Do Not Track and tracking protection are two separate things:
Do Not Track is enabled in Preferences/Options > Privacy > "Tell sites that I do not want to be tracked". Enabling sends the DNT header but it does not block any requests.
Tracking Protection is enabled in about:config > privacy.trackingprotection.enabled. Enabling does not send the DNT header, but does block requests based on Disconnect's blocklist. So detecting 2 isn't as easy as checking navigator.doNotTrack, because that property is only set for 1.
Solution (temporarily) - try to do FB.init, if error do some alert..
try {
FB.init({
appId: '{$appid}',
status: true,
cookie: true,
xfbml: true,
oauth: true
});
}catch(err) {
alert('Some info for the user...');
}
Does anyone have better solution?
A simple google search leads to this page: https://developer.mozilla.org/en-US/Firefox/Privacy/Tracking_Protection
You should be able to deactivate that feature right where the message appears, or via about:config. It should actually be deactivated by default afaik.
From the client side, you can't. This is security policy Firefox. You can read about this issue in thread: https://bugzilla.mozilla.org/show_bug.cgi?id=1226498
If any one is coming to this post to find how to handle this error. I think this answer may help.
(function (d, s, id) {
let js,
fjs = d.getElementsByTagName(s)[0];
if (d.getElementById(id)) {
return;
}
js = d.createElement(s);
//here goes the error handling
js.onerror = (e) => {
//here we can handle the error
//we can show the user why the page isn't loading correctly
}
js.id = id;
js.src = 'https://connect.facebook.net/en_US/sdk.js';
fjs.parentNode.insertBefore(js, fjs);
})(document, 'script', 'facebook-jssdk');
A way to go about it is checking whether the FB object exists after all script resources have been loaded. In this way we are covered regardless of what caused the script load failure:
$(window).on("load", function() {
// If Facebook SDK failed to load ...
if (typeof FB === "undefined") {
// ... then change interface/set global variable to handle missing FB
}
});

Register gcm for chrome

I have a chrome Apps use push notification of GCM. I have a problem, when i don't login account on chrome. I can't receive registerId from GCM. I think a idea. When registerId empty, i show notification, request user login to chrome and show login page account on chrome. But because of security concerns , the chrome does not allow access to its setting from external links . How is open "chrome://settings/" from external links? Can register to gcm, If i don't want login account on chrome?
My code:
function setValue()
{
//var thongtin=$('#status').val();
//var thongtin = document.getElementById('status').innerText;
if(registrationId == "")
{
// Pop up a notification to show notification.
chrome.notifications.create(getNotificationId(), {
title: 'CLOUD MONITOR',
iconUrl: 'gcm_128.png',
type: 'basic',
message: 'You must sign in account gmail on google chrome!'
}, function() {});
//event click to notification
chrome.notifications.onClicked.addListener(function() {
window.location.href = "chrome://settings/"
});
}
else
{
//http://mtraffic.longvan.net/device_register?regId=" +registrationId+"&device=android
//document.getElementById('webviewSendData').src = "http://192.168.64.246:8080/register?REGID=" +registrationId+"&DEVICE=desktop";
document.getElementById('webviewSendData').src = "http://mtraffic.longvan.net/device_register?regId="+registrationId+"&device=android";
//document.getElementById('webviewSendData').src = "http://192.168.64.124:8080/monitor/device_register?regId=" +registrationId+"&device=android";
//var url = "http://192.168.64.124:8080/monitor/device_register?regId=" +registrationId+"&device=android";
//httpGet(url);
//alert(thongtin);
//document.getElementById('status').innerHTML="Infomation New";
// Pop up a notification to show notification.
}
}
This code don't run.
chrome.notifications.onClicked.addListener(function() {
window.location.href = "chrome://settings/"
});
I fix code as Derek 朕會功夫.
chrome.notifications.onClicked.addListener(function() {
chrome.tabs.create({url: "chrome://settings/"});
});
And receive error notify: Error in event handler for notifications.onClicked:TypeError: Can't read property 'create' of underfined.
I'm afraid at the moment it's not possible.
Chrome Apps don't have access to tabs/windows API that can open privileged pages; that's why Derek's suggestion does not work.
In future, they may be a way to do this with chrome.browser API. See this feature request, this proposal, and please leave feedback there with your use case.

Adobe DPS Android Entitlement

We are stuck with an Adobe DPS project. We cant get our DPS android app to do Entitlement for our print subscribers and we were wondering if anyone out there has managed to get this right.
We've used Adobe's tutorial here:
http://www.adobe.com/devnet/digitalpublishingsuite/articles/library-store-combined-template.html, with isEntitlementViewer set to true.
The code asks for a username and password and then via Adobe's API AdobeLibraryAPI.js, it authenticates a user via our own API. the very same code is working 100% in the iPad version of the app.
The file that actually processes the login (called LoginDialog.js) contains the following code within a function called clickHandler (we’ve added a few javascript alerts to try debug the login process)
// Login using the authenticationService.
var transaction = adobeDPS.authenticationService.login($username.val(), $password.val());
alert("1: "+transaction.state ); //returns “1: 0”
transaction.completedSignal.addOnce(function(transaction) {
alert("2: "+transaction.state ); //never returns
var transactionStates = adobeDPS.transactionManager.transactionStates;
if (transaction.state == transactionStates.FAILED) {
$("#login .error").html("Authentication Failed.")
} else if (transaction.state == transactionStates.FINISHED){
this.$el.trigger("loginSuccess");
this.close();
}
alert("3: "+transaction.state ); //never returns
}, this);
alert("4: "+transaction.error ); //never returns
Anyone out there with some DPS/android/Entitlement experience?
Android Entitlement only works after an integrator ID is registered with Adobe, as the android viewers service routes are only configured via the integrator ID.
If you do not have an integrator ID, you need to acquire one from Adobe Support.
Also it is worth mentioning, that in contrary to iOS, Android DPS viewers only support one base Route/URL for Authentication and Entitlements.
For Example whereas in iOS you can have the login been done via the first URL:
https://example.com/api/v1/SignInWithCredentials
The second URL for entitlements can be on a different URL:
http://server2.example.com/v1/api/entitlements
In android both URLs have to be the same, e.g.:
https://example.com/api/v1/SignInWithCredentials and
https://example.com/api/v1/entitlements

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.

Categories

Resources