I am developing an iOS app with Cordova and I am using the Facebook-connect plugin for authentification.
My problem : sometimes the Facebook Plugin doesn't load early enough so the FB authentification doesn't go the native way, but through a kind of in-app browser popup.
Is there a way to detect that Fb plugin has finished loading ?
Thank you
I think you should use facebook phonegap plugin as your authentication.
Download and install into your cordova project.
https://github.com/phonegap/phonegap-facebook-plugin
Then make sure you have this script in your project.
cdv-plugin-fb-connect.js
facebook-js-sdk.js
After that, paste this code into your main script
if ((typeof cordova == 'undefined') && (typeof Cordova == 'undefined')) alert('Cordova variable does not exist. Check that you have included cordova.js correctly');
if (typeof CDV == 'undefined') alert('CDV variable does not exist. Check that you have included cdv-plugin-fb-connect.js correctly');
if (typeof FB == 'undefined') alert('FB variable does not exist. Check that you have included the Facebook JS SDK file.');
FB.Event.subscribe('auth.login', function(response) {
//alert('auth.login event');
});
FB.Event.subscribe('auth.logout', function(response) {
//alert('auth.logout event');
});
FB.Event.subscribe('auth.sessionChange', function(response) {
//alert('auth.sessionChange event');
});
FB.Event.subscribe('auth.statusChange', function(response) {
//alert('auth.statusChange event');
});
function getSession() {
alert("session: " + JSON.stringify(FB.getSession()));
}
function getLoginStatus() {
FB.getLoginStatus(function(response) {
if (response.status == 'connected') {
alert('logged in');
} else {
alert('not logged in');
}
});
}
var friendIDs = [];
var fdata;
function logout() {
FB.logout(function(response) {
alert('logged out');
window.location.replace("#login");
});
}
function login() {
FB.login(
function(response) {
if (response.authResponse) {
alert('logged in');
FB.api('/me', function(me) {
if (me.id) {
localStorage.id = me.id;
localStorage.email = me.email;
localStorage.name = me.name;
window.location.replace("#home");
}
else {
alert('No Internet Connection. Click OK to exit app');
navigator.app.exitApp();
}
});
} else {
alert('not logged in');
}
}, {
scope: "email"
});
}
document.addEventListener('deviceready', function() {
try {
//alert('Device is ready! Make sure you set your app_id below this alert.');
FB.init({
appId: "appid",
nativeInterface: CDV.FB,
useCachedDialogs: false
});
document.getElementById('data').innerHTML = "";
} catch (e) {
alert(e);
}
}, false);
use login() to login . Enjoy!!
There must be an entry in the log, if the plugin fails to load while testing the app.
Also looks like you are using facebook API, phonegap other native plugins always load after the recommended plugins offered in here.
Also it loads as per the order you mentioned in the XML file,
<feature name="org.apache.cordova.facebook.Connect">
<param name="ios-package" value="FacebookConnectPlugin" />
</feature>
and
<plugin name="" value="" />
As developers clearly knows debugging in Phonegap is difficult than pushing a tanker.
Hope the following invoking method helps,
Add the reference of your plugin to your index.html
After the onDeviceReady() function, add the JavaScript for invoking the native plugin and handling the plugin results.
Add JavaScript functions named callNativePlugin, nativePluginResultHandler, andnativePluginErrorHandler
as shown below,
function callYourPlugin( returnSuccess ) {
YourPlugin.callNativeFunction( YourPluginResultHandler, YourPluginErrorHandler, returnSuccess );
}
function YourPluginResultHandler (result) {
alert("SUCCESS: \r\n"+result );
}
function YourPluginErrorHandler (error) {
alert("ERROR: \r\n"+error );
}
Finally add buttons to invoke your plugins as follows,
<body onload="onBodyLoad()">
<h1>Hey, it's Cordova!</h1>
<button onclick="callYourPlugin('success');">Click to invoke the Native Plugin with an SUCCESS!</button>
<button onclick="callYourPlugin('error');">Click to invoke the Native Plugin with an ERROR!</button>
</body>
I feel this method as easy to invoke any plugins, also you can checkout this article for more.
Related
This code has been working fine, but now it's working intermittently in chrome. Does anyone know what might be causing this. If so what can I do to increase stability in chrome
This function opens a pop up modal with the project form react component.
editProject: function(i) {
$('#agency_projects').trigger(
"projects:open",
[this.state.projects[i].showUrl, true]
);
},
getInitialState: function() {
return {
...
/* TODO Refactor to prevent props in initialState */
projectId: this.props.projectId,
projectUrl: this.props.projectUrl,
}
},
The initial state has the project id, and url stored which is used to submit an ajax request to pull in the project.
componentDidMount: function() {
if(this.props.projectUrl) {
$.getJSON(this.state.projectUrl)
.done(function(data) {
if(!this.isMounted()) {
return;
}
this.setState({
title: data.title,
externalUrl: data.externalUrl,
client: data.client,
description: data.description,
content: data.content,
});
}.bind(this))
.fail(function(jqXHR, status, err) {
console.error(jqXHR, status, err);
});
}
},
The form renders as suspected, but the data is only pulled every now and again.
Im using Phonegap 2.9.0 in ios, i have gone through the tutorial for inappbrowser .and i have tried the following to in my application
App.js Calling method
indexpnl.element.on({
tap: function (e) {
var el = Ext.get(e.target);
var bval = el.getId();
if (bval == "btnfacebook") {
// onDeviceReady()//using this application screen its self loading the site view not in inappbrowser
document.addEventListener("deviceready",onDeviceReady, false);//here nothing happening
}
}
});
jsfunction.js Method
function onDeviceReady()
{
var ref = window.open('http://www.facebook.com', '_blank', 'location=yes');
ref.addEventListener('loadstart', function() { alert('start: ' + event.url); });
ref.addEventListener('loadstop', function() { alert('stop: ' + event.url); });
ref.addEventListener('exit', function() { alert(event.type); });
}
And i have include the plug in config.xml
<feature name="InAppBrowser">
<param name="ios-package" value="CDVInAppBrowser" />
</feature>
When i call using the above method nothing happens.When i call On onDeviceReady() the site is loading in application itslef but not in the inapp browser.What wrong with my code
Dunno but have you checked you have a
<script src="phonegap.js"></script>
in your script as in
https://build.phonegap.com/docs/plugins-using
Leaving it out can produce those kind of errors
I'm trying to save the state of a jQuery toggle in a Rails app with little success. How would I store it in a session? Or would I store it in a cookie? Thanks for your help.
Here's the jQuery that handles the toggle:
$(function() {
function showHideDocuments() {
$("#accordion").toggle("blind", 500);
};
$("#finalised-documents").click(function() {
showHideDocuments();
return false;
});
});
I don't really know how to proceed from here. Thanks!
For anyone else struggling with this, here's a solution. Use the jQuery cookie plugin with this code:
$(document).ready(function() {
$('#finalised-documents').click(function () {
if ($('#accordion').is(':hidden')) {
$('#accordion').slideDown(500);
$.cookie('forgetmenow', 'showing');
} else if ($('#accordion').is(':visible')) {
$('#accordion').slideUp(500);
$.cookie('forgetmenow', 'hidden');
}
});
if($.cookie('forgetmenow') == 'hidden') {
$('#accordion').hide();
};
});
Enjoy.
I am trying to build a web app that will allow a user to login Facebook. Everything works in Firefox/Chrome/Safari (on the phone/tablet and on OSX).
When the App runs on the tablet (Native UIWebview and Web-app) it loads the first page perfectly.
When the user clicks the "connect with Facebook" button the app loads the Facebook logon page.
After the user logs in (again, in both a Native UIWebview and a web-app) the view turns white hanging on the URL: 'https://www.facebook.com/dialog/permissions.request?_path=permissions.request&app_id=[APP_ID]...' - this seems like it should not happen...
If I restart the app/web-app the user is logged in automatically, and redirected to the success page.
What I think is causing the problem
When you run the web page in the Firefox/Chrome/Safari browsers the Facebook login Dialog pops up as a popup or another tab (the latter on the native Safari browser).
I believe that this is a problem with this popup page and how the Javascript communicates with itself when a successful login takes place. Something with window.close where there is no root page to return to (as the web-app and UIWebview only have one instance of the webview)... maybe?
Failed work-around (UIWebview)
Since the app was hanging up on the previously mentioned URL I decided to add an if statement in shouldStartLoadWithRequest(...) to force the UIWebview to go to the success URL.
It loads the URL, but then before Facebook's Javascript SDK function FB.getLoginStatus function returns 'Connected' (It does return 'Connected' every time I've seen) The function FB.Event.subscribe('auth.logout' function() {...}); is fired.
I don't understand why it is logging the user out, then telling me that the user is connected (logged in) - in that order.
Any Ideas before I embark on trying to build this 100% native (and have to put up with apple's dev account and submitting the app)?
Login Script
<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=APP_ID";
fjs.parentNode.insertBefore(js, fjs);
}(document, 'script', 'facebook-jssdk'));</script>
<script>
var seccond_page = false;
window.fbAsyncInit = function() {
FB.init({
appId : '[APP_ID]',
status : true,
cookie : true,
xfbml : true,
oauth : true
});
FB.Event.subscribe('auth.login', function(response) {
window.location.href = '<?= $success ?>';
});
FB.Event.subscribe('auth.logout', function(response) {
window.location.reload();
});
FB.login(function(response) {
alert(response.status);
if (response.status) {
if (response.status == 'connected') {
window.location.href = '<?= $success ?>';
}
}
}, {scope: 'email, user_likes, user_status, user_birthday, user_location, publish_checkins'});
$(document).on('click', '#fb_login_button', function() {
FB.login();
});
};
</script>
Success Page
<script>
var fb_user_id = '';
var fb_access_token = '';
var user_location = '';
window.fbAsyncInit = function() {
FB.init({
appId : '[APP_ID]',
status : true,
cookie : true,
xfbml : true,
oauth : true
});
FB.getLoginStatus(function(response) {
alert('Response - ' + response.status);
// the auth.logout is fired before the return of this in the failed fix
if (response.status === 'connected') {
if (response.authResponse) {
fb_user_id = response.authResponse.userID
fb_access_token = response.authResponse.accessToken;
}
}
});
FB.Event.subscribe('auth.logout', function(response) {
alert('logout - auth.logout');
// This event is fired before the above function in the failed fix
window.location.href = '<?= site_url('fb_login'); ?>';
});
FB.Event.subscribe('edge.create', function(response){
if (response == '<?= $like_url ?>') {
//action
}
});
};
</script>
All pages have the meta tag: <meta name="apple-mobile-web-app-capable" content="yes">
Facebook calls auth.logout just before auth.login for reasons not clear to me. You should inspect the response parameter before assuming that the user really has been logged out. Facebook docs state:
auth.logout - fired when the user logs out. The response object passed into the callback function looks like:
{
status: "", /* Current status of the session */
}
If you execute your logout handling only if response.status is really "", you may find that during login, it calls auth.login listeners immediately after calling the auth.logout listener. Your current auth.logout handling prevents you from noticing this, because the page reload stops JS and ajax executions.
Can the current Facebook Javascript SDK work with older Facebook API library?
Right now there is code to load the current Facebook Javascript SDK by:
window.fbAsyncInit = function() {
FB.init({appId: '218565466928', status: true, cookie: true,
xfbml: true});
};
// [...] initialize it
And there is code to use the old Facebook API by
init_fb_connect('Connect', 'XFBML', :js => :jquery, :app_settings=> '{ifUserNotConnected: fb_user_not_connected}' ) do
which is the Facebooker Rubygem. Can they work together somehow? If I have both, then the newly added "Like" button won't work. If I remove the older Facebooker code, then the "Login with Facebook" and "Share" button won't work. Any ideas?
Update: the older code do things like:
<a class="facebook-connect-link " href="#"
onclick="; FB.Connect.requireSession(fb_after_connect, null, true); return false;"
rel="nofollow">Sign in with Facebook</a>
and
<a href="#" onclick="FB.Connect.streamPublish('', {'name': 'Some product name' ...
and
$('.login-button').each(function() {
FB.XFBML.Host.addElement(new FB.XFBML.LoginButton(this));
})
Converting the JavaScript API is relatively easy. I am not sure how much your server side will be affected though. Here are the basic methods that you would probably need:
//Check if user is logged in right now.
FB.getLoginStatus(function(response) {
if (response.session) {
// logged in and connected user, someone you know
} else {
// no user session available, someone you dont know
}
});
//Callback fired when user logs out/logs in.
FB.Event.subscribe('auth.sessionChange', function(response) {
// do something with response.session
});
//To force login (on login btn click).
FB.login(function(response) {
if (response.session) {
// user successfully logged in
fb_after_connect();
} else {
// user cancelled login
}
});
//Post to feed.
FB.api('/me/feed', 'post', { body: "message" }, function(response) {
if (!response || response.error) {
alert('Error occured');
} else {
alert('Post ID: ' + response);
}
});
If you don't want to convert to the new API then you can embed like button as iframe. Sooner or later you would have to convert your project anyway so might as well do it now.