phonegapFacebookApp

Adding a social layer to your app can be a really great thing, it can help users share their experience with others. Getting Facebook and Twitter integrated into your app should be an easy task right? Currently the phonegap plugin for Facebook is lacking, which is a bummer, but never fear there is always a work around!

If you’ve already read the Twitter App Tutorial you have a pretty good idea of how this will work. It follows the same idea and actually is quite similar.

Let’s get started!

Setup

1. Download the project from GIT

2. Create a new phonegap project in xCode.

3. Once you’re all set up open up the phonegapFacebookApp files from GIT

4. In your WWW folder create a new folder called “js” inside of that create two other folders “core”, and another called “plugins”.

5. Copy the files from the phonegapFacebookApp the js/core, js/plugins, and images folders into your www folder.

6. create a new js file called “init.js” in the root of your js folder.

so at this point you should have a file structure that looks like this…

 

 

 

Setup pt2. ( phonegap plugins )

1. In the phonegapFacebookApp project folder select the following files -

ChildBrowserCommand.m
ChildBrowserCommand.h
ChildBroswerViewController.m
ChildBrowserViewController.h

 

 

Drag those into xcode into the “plugins folder.

 

 

Now go to your PhoneGap.plist file and we need to add a couple things.

1. Add a new external host, the key is not important but set the value to * ( this is a catch all for all domains )

2. add ChildBrowserCommand to your plugins, as both the key and value.

 

 

 

Setting Up Facebook
1. Go to www.developers.facebook.com
2. click apps and then “Create new App”
3. Fill out your app name and information
4. Once your app is created go down to the area that says “Select how your app integrates with Facebook”
5. Click “website” and put a url, this can be your URL or your apps URL ( really this doesn’t matter but Facebook requires it )

6. Now click on the “advanced” settings on the right hand side.
7. Disable “depreciated offline access” – We are requesting a long lived token, and will need offline access.

Okay now let’s make our app!

CODE
Let’s start with our index.html

<!DOCTYPE html>
<html>
  <head>
  <title></title>
 
    <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no;" />
	<meta charset="utf-8">
	<script type="text/javascript" charset="utf-8" src="phonegap-1.2.0.js"></script>
 
    <!-- CORE JS FILES -->
    <script type="text/javascript" charset="utf-8" src="js/core/phonegap-1.2.0.js"></script>
    <script type="text/javascript" charset="utf-8" src="js/core/jQuery.js"></script>
 
    <!-- PLUGINS -->
    <script type="text/javascript" charset="utf-8" src="js/plugins/ChildBrowser.js"></script>
 
    <!-- OUR INIT -->
    <script type="text/javascript" charset="utf-8" src="js/init.js"></script>
 
    <!-- STYLE STUFF -->
    <link rel="stylesheet" href="css/style.css" />
 
  </head>
  <body onload="app.bodyLoad()"> <!-- CALL TO OUR JS TO LET IT KNOW THE APP IS LOADED -->
  		<div id="header"></div>
  		<div id="loginArea"> <!-- If we don't have a user we will show this -->
			<div id="login" class="btn">Login</div>
        </div>
        <div id="status"> <!-- if we do have a user we will show this -->
        <div id='statusHold' style='text-align:center; width:100%;'><img src='images/loader.gif' id="info"/></div>
        	<textarea id="statusTXT"></textarea>
            <div id="statusBTN" class="btn">share</div>
        </div>
  </body>
</html>

Now if you haven’t already create a file in your css folder called style.css

* {
	margin:0px;
}
body {
	font-family:Helvetica;
	-webkit-user-select: none;
	background-color:#f3f3f3;
}
#wrapper {
	width:100%;
	height:100%;
	padding-top:15px;
}
#header {
	height:150px;
	width:100%;
	background-image:url(../images/header.png);
	background-size:100%;
	margin-bottom:35px;
}
#loginArea {
	width:100%;
	display:none;
}
.btn {
	font-size:25px;
	text-align:center;
	padding-top:12px;
	padding-bottom:12px;
	width:95%;	
	border-radius: 5px;	
	background-color:#305d9a;
	margin:auto;
	color:#fff;
	font-weight:bold;
	box-shadow: 0px 0px 2px .6px #222222;
}
#status {
	width:100%;
	display:none;
	text-align:center;
}
#status textarea {
	border:1px solid #cccccc;
	width:94%;
	height:75px;
	margin:auto;
}
#info {
	display:none;
}

Okay now that it looks good let’s make it do stuff!

Open your init.js file from your js folder.

First we need to set up our global variables

// GLOBAL VARS
var my_client_id = "XXXXXXXXXXXXXXXXXXXXXXX", // YOUR APP ID
	my_secret = "XXXXXXXXXXXXXXXXXXXXXXX", // YOUR APP SECRET 
	my_redirect_uri = "http://www.facebook.com/connect/login_success.html", // LEAVE THIS
	my_type ="user_agent", my_display = "touch"; // LEAVE THIS
 
var facebook_token = "fbToken"; // OUR TOKEN KEEPER
var client_browser;

Now let’s add the Facebook object, I like to create one object that controls all sharing.

// FACEBOOK
var Facebook = {
	init:function(){
 
		// Begin Authorization
		var authorize_url = "https://graph.facebook.com/oauth/authorize?";
		 authorize_url += "client_id=" + my_client_id;
		 authorize_url += "&redirect_uri=" + my_redirect_uri;
		 authorize_url += "&display=" + my_display;
		 authorize_url += "&scope=publish_stream,offline_access"
 
		 // Open Child browser and ask for permissions
		 client_browser = ChildBrowser.install();
		 client_browser.onLocationChange = function(loc){
			 Facebook.facebookLocChanged(loc);
		 };
		 if (client_browser != null) {
			window.plugins.childBrowser.showWebPage(authorize_url);
		 }
	},
	facebookLocChanged:function(loc){
 
		// When the childBrowser window changes locations we check to see if that page is our success page.
		if (loc.indexOf("http://www.facebook.com/connect/login_success.html") > -1) {
			var fbCode = loc.match(/code=(.*)$/)[1]
			$.ajax({
				url:'https://graph.facebook.com/oauth/access_token?client_id='+my_client_id+'&client_secret='+my_secret+'&code='+fbCode+'&redirect_uri=http://www.facebook.com/connect/login_success.html',
				data: {},
				dataType: 'text',
				type: 'POST',
				success: function(data, status){
 
					// We store our token in a localStorage Item called facebook_token
					localStorage.setItem(facebook_token, data.split("=")[1]);
 
					window.plugins.childBrowser.close();
 
					app.init();
				},
				error: function(error) {
					window.plugins.childBrowser.close();
				}
			});
		}
	},
	share:function(url){
 
		// Create our request and open the connection
		var req = new XMLHttpRequest(); 
		req.open("POST", url, true);
 
 
		req.send(null); 
		return req;
	},
	post:function(_fbType,params){
 
		// Our Base URL which is composed of our request type and our localStorage facebook_token
		var url = 'https://graph.facebook.com/me/'+_fbType+'?access_token='+localStorage.getItem(facebook_token);
 
		// Build our URL
		for(var key in params){
			if(key == "message"){
 
				// We will want to escape any special characters here vs encodeURI
				url = url+"&"+key+"="+escape(params[key]);
			}
			else {
				url = url+"&"+key+"="+encodeURIComponent(params[key]);
			}
		}
 
		var req = Facebook.share(url);
 
		// Our success callback
		req.onload = Facebook.success();
	},
	success:function(){
		$("#statusTXT").show();
		$("#statusBTN").show();
 
		// hide our info
		$("#info").hide();
 
		// reset our field
		$("#statusTXT").val('');
 
		console.log("DONE!");
 
	}
};

Before we move on lets look at what we created in that Facebook object. You’ll notice the post function.

  • Facebook.post(_fbType,params);
    • _fbType is the type of request you want to make to Facebook in our example it’s ‘feed’
    • params are the arguments for that method, the script will parse them out and assemble the correct query URL

Awesome.
Okay last step lets make our app object

// APP
var app = {
	bodyLoad:function(){
		document.addEventListener("deviceready", app.deviceReady, false);
	},
	deviceReady:function(){
		app.init();
	},
	init:function(){
		// First lets check to see if we have a user or not
		if(!localStorage.getItem(facebook_token)){
			$("#loginArea").show();
			$("#status").hide();
 
			$("#login").click(function(){
				Facebook.init();
			});
		}
		else {
			console.log("showing loged in");
			$("#loginArea").hide();
			$("#status").show();
 
			$("#statusBTN").click(function(){
				if($("#statusTXT").val() == ""){
					alert("make sure you've filled out the text area!");
				}
				else {
					// hide our assets
					$("#statusTXT").hide();
					$("#statusBTN").hide();
 
					// show our info
					$("#info").show();
					app.createPost();	
				}
			});
		}
	},
	done:function(){
 
	},
	createPost:function(){
 
 
		// Define our message!
		var msg = $("#statusTXT").val();
 
		// Define the part of the Graph you want to use.
		var _fbType = 'feed';
 
		// This example will post to a users wall with an image, link, description, text, caption and name.
		// You can change
		var params = {};
			params['message'] = msg;
			params['name'] = 'A Facebook App for Phonegap';
			params['description'] = "I just made a Facebook app with Phonegap using this sweet tutorial from Drew Dahlman";
			params['_link'] = "http://www.drewdahlman.com";
			params['picture'] = "http://compixels.com/wp-content/uploads/2011/04/Facebook-Logo.jpg";
			params['caption'] = 'Hello World';
 
		// When you're ready send you request off to be processed!
		Facebook.post(_fbType,params);	
	}
};

What we do with this is control our whole application. When it’s loaded it first checks to see if our localStorage item facebook_token is there, if not then it shows the login button. If the facebook_token is there then it shows a status box.

When the share button is clicked it goes to the app.createPost() function. This will take the message in the status box and fill up the params JSON object, then pass it to our Facebook object to parse and post.

You could in theory make every param dynamic, in this example I’ve hard coded them.

So now that everything is set let’s save our files and compile our project!

BAM! there you go, now you can post to Facebook from a phonegap app, remember you can also extend this to work with other Facebook Methods! Play around and experiment!

DOWNLOAD PROJECT

This entry was posted in facebook, phonegap and tagged , , . Bookmark the permalink.

75 Responses to phonegapFacebookApp

  1. michael says:

    Awesome tutorial!… There is a typo in setup pt2 at the end ‘ChildBroswerCommand’ – > ‘ChildBrowserCommand’

    • Drew says:

      :) glad you liked it! Thanks for the heads up! Fixed :P

      • michael says:

        I hit a snag when building. childBrowser keeps saying ‘PhoneGapViewController* is deprecated’. I updated to the latest phone gap build, which may have caused this. Would you happen to know a workaround for this?

        Thanks!

        • Drew says:

          I am looking into this, looks like they’ve changed it to run as a component now and with that they’ve changed PhoneGapViewController to PGViewController.

          replace the reference in ChildBrowser to
          #ifdef PHONEGAP_FRAMEWORK
          #import #else
          #import “PGViewController.h”
          #endif
          They have included a PDF that goes over how to use PhoneGap now in the DMG for 1.4

          Also any other references to PhoneGapViewController I will update the project to reflect this

  2. Waleed Khan says:

    thnks for that wonderfull tutorial….

    i want to go further in it… tell me how can i access my friends, wall in phonegap

  3. Siebmanb says:

    You are the best ! Thanks so much.

  4. Siebmanb says:

    Small precision for people using Phonegap with Sencha Touch : the above code is using jQuery and not EXTJs, be careful !

    • Drew says:

      Yes this does use jQuery, but you can totally modify it to use any markup really. If you use the base ideas of ajax, and localStorage everything should work. I am using jQuery for ajax and showing and hiding things, it’s up to you how you implement the code though

  5. Paul says:

    Great tutorial!

    However, I’ve run into an issue with the Login button. It crashes my app when I press it. Screen turns black. ChildBrowser doesn’t come up, it just goes black. I’m not getting any errors in the log either!

    This only happens when I build to my Ipad (iOS 5.0.1) device and not in the simulator. Weird?!

    I’m building with jQuery Mobile 1.0.1, PhoneGap 1.3.0, Xcode 4.2.

    Any suggestions would be appreciated!

    I’ll post the solution here if I find it.

  6. J says:

    Everything works fine until I run the app and click the login button. Then the app just hangs with a blank (black ) screen. The authorize_url is correct, I can open it in a browser, or in another test app that I was trying ChildBrowser with. I’m using PG 1.2, Xcode 1.4.

    Any help would be appreciated.

    • Paul says:

      I had the same problem. Turns out, for me, that you have to use the ChildBrowserViewController.xib and the ChildBrowser.bundle files as well. Make sure you right click the Plugins folder and add them in that way. Then Project>Clean and build again.

  7. Paul says:

    Is anyone else getting a blank/white page with “Success” in the top-left corner after logging in to Facebook??

    I’ve researched this and it’s a problem for developers and users alike with Facebook Connect.

    Anyone know of a solution for developers using Phonegap for iOS?

    Thanks!

    • Drew says:

      Hey Paul,
      Glad you were able to figure out the childbrowser thing!

      So since the redirect URL is “http://www.facebook.com/connect/login_success.html” that’s why you see the success text in the corner. You can change this to be any page really. For this example that’s just what I used.

      Hope that helps!

      • Paul says:

        Thanks Drew for your response!

        I figured that it has something to do with where the URL is directing, but I according to the code in the Init.js and the HTML as well, the user’s experience after logging on successfully is supposed to be directed to their status as well as a “Share” button with the ability for them to post my message to their wall. Is that correct? If so, how do I do this?

        Also, if I press the done button, it just goes back to my page the blue “login” button. According to the console log, it says: “New Address is : about:blank”.
        However, this is where the user is supposed to be able to go back into the app, and it does, so I don’t think that is where the issue is.

        Any help or guidance would be appreciated!

        • Drew says:

          Hmmm so in the example what we’re doing is making a request to FB, if you get the success message that means you’ve gotten permission from FB to post to the wall. Which means the status area should show up and the login goes away..

          in the facebookLocChanged function we’re listening to the new URL that childbrowser has gone to. If it matches the string in there – the example here is – http://www.facebook.com/connect/login_success.html and if that’s the url then it will pull off the token and save it as a localStorage item for use later. It should also close the childBrowser.

          Sounds like the redirect isn’t working properly or if you have changed the redirect_url in our global vars, then make sure that URL is reflected in the localChange function.

          I suggest doing a console log in the location change function and see what it’s coming out with…

          • Paul says:

            No, I didn’t change the Javascript. The only alterations I did were where I put in my AppID and ClientID.

            It does redirect to the right URL, but with a long string at the end?

            This is what the log is showing:

            New Address is : https://www.facebook.com/connect/login_success.html?code=AQCdIdPq9LU-73coN_6A5rz8A75-0Ra854weMx7pkRBlkSPqiOhPRWZmwwXxLgy68cGSzppGo4bSeM7SCh1g8wre0pFdOVRMpfIEs1yCKoX5iCVcPUvLMUnMLxe-ZKaMYPS6K4Tf50mu96pQBZasuQJVfE_HoLhD94u4pe5crH-8MIDmpiCAwsDpOkumcDwvEyk#_=_

            Looking back in my project, I remember that I’ve altered the ChildBrowser plugin files (almost all to some degree), according to different sources that I found on the net.

            Since there is an issue with the ChildBrowser closing, I remembered that I made the following change to the ChildBrowser.js:

            c. click the ChildBrowser.js file in XCode…
            look for this bit of code:


            // Callback when the user chooses the 'Done' button
            // called from native
            ChildBrowser._onClose = function()
            {
            window.plugins.childBrowser.onClose();
            };

            i changed:
            window.plugins.childBrowser.onClose();
            to
            window.plugins.childBrowser.onClose = close;

            However, I tested it both ways and no change.

            Also, just to let you know, that I have duplicate projects. One using your method for Facebook connect and the other “official PhoneGap plugin” for Facebook connect. Everything else is the same. So far, both are having this issue with the “blank Success page” after the user logs in.

            I’m going to go back and look at every change I’ve made to the ChildBrowser files and test!

    • Drew says:

      Hey Paul,
      I am updating the git project to fix this issue! The problem is that the redirect URL is http and in the location change function it’s looking for http but if you have security settings in facebook that are running on https the script wont work!

      SO the big change is adding https:// to both the redirect url and the location change functions you should be all set :)

      Drew

  8. Paul says:

    Drew, you are the man!

    I changed the Global var as well, for a total of three times in the code. Works!

    I’m sure I would’ve figured it out eventually, probably like at 3 am. ha! Thanks for saving me a bunch of time and for the write up!!

    Paul

  9. Paul says:

    Just wanted to share for those who may want to add an alert of success after the user posts to Facebook.

    I added one line of code in the Init.js:

    From this:


    success:function(){
    $("#statusTXT").show();
    $("#statusBTN").show();

    // hide our info
    $("#info").hide();

    // reset our field
    $("#statusTXT").val('');
    console.log("DONE!");
    }
    };

    To this:

    success:function(){
    $("#statusTXT").show();
    $("#statusBTN").show();

    // hide our info
    $("#info").hide();

    // reset our field
    $("#statusTXT").val('');

    console.log("DONE!");
    alert("Successfully shared on Facebook (check your status!)");
    }
    };

  10. Thomas says:

    Hello,
    first of all – thanks for the plugin!

    I always get an error from the ajax request to login – what i’m doing wrong? app settings in facebook? i’ve disable “depreciated offline access” …i get the success screen – then the childbrowser close from the error and nothing else happen! any solution?

  11. Thomas says:

    In Phonegap: my_redirect_uri = “https://www.facebook.com/connect/login_success.html”
    in facebook: http://mydomain.com

    • Drew says:

      this is going to sound crazy but just try this – for your facebook app set the domain to http://www.youractualdomain.com/ the slash at the end is important. give that a shot and let me know

    • Drew says:

      Hey Thomas, So I am working on a new tutorial about twitter and facebook and phonegap and ran into this exact problem!

      Here is the quick fix for you right now – I should have the tutorial up later today and explain in more depth!

      first change your my_redirect_uri to “http://www.facebook.com/connect/login_success.html”

      in your locataionChange function replace this line

      if (loc.indexOf("http://www.facebook.com/connect/login_success.html") > -1)

      with this

      if (loc.indexOf("http://www.facebook.com/connect/login_success.html") > -1 || loc.indexOf("http://www.facebook.com/connect/login_success.html") >= 0)

      basically this is an issue similar to what Paul faced, the problem is the users security settings, if you are using Facebook with security it uses HTTPS vs HTTP and when the request comes back it uses your settings and can screw things up. Adding this will resolve the issue!

  12. Thomas says:

    hey drew,

    thanks, now i can test the plugin, but its works only if i disable “https” in my facebook user settings! :-(

    with https – i see the “success” screen – and the browser doesn’t close!

    • Paul says:

      Thomas,

      The way I have it working is with the “https” included in the redirect uri in the Global Vars and twice in the locataionChange function. Once in the ajax call as well.

      $.ajax({ url:'https://graph.facebook.com/oauth/access_token?client_id='+my_client_id+'&client_secret='+my_secret+'&code='+fbCode+'&redirect_uri=https://www.facebook.com/connect/login_success.html',
      

      Don’t know if you have to do that as well? Worked for me.

      • Paul says:

        OK, just tested. Yes you do need to change the url in the above code as well. For a total of three times.

        My childbrowser did close, but the Facebook “login” button didn’t change to the “share” button.

      • Thomas says:

        ahh yes that worked for me too..great!

        thank you for your help, this script is amazing, it work with other facebook methods so easy, exactly what i was looking for!

  13. J says:

    Anybody come up with a Logout functionality?

    Was trying something like this (#logout is just a text link), but it doesn’t work consistently.

    $(“#logout”).click(function(){
    localStorage.removeItem(facebook_token);
    alert(“logged out”);

    $(“#loginArea”).show();
    $(“#status”).hide();
    $(“#logout”).hide();
    app.init();
    });

    • J says:

      Think I got it, with some help from stack overflow. Needed to delete Childbrowser’s cookies. Modified their code slightly, so that I add this to the Facebook object in Drew’s code:

      logout:function() {
      window.plugins.childBrowser.LogOut();
      }

      and call Facebook.logout();

      • Drew says:

        awesome! Nice addition! I will add this to the code, I have made a few improvements to this as well, hopefully have that up soon!

        • J says:

          Drew, have had a chance to work with this at all? Thought I had it working pretty well, but the logout works sporadically. Specifically looks like it fails here:
          (this is in the Facebook object, function I added from comment above)

          logout:function() {

          window.plugins.childBrowser.LogOut();

          }

          Any ideas?

          • Drew says:

            Hi Jason,
            I haven’t tried the childBrowser logout, but for my apps I just remove the localStorage(facebook_token) and everything works fine. What happens that makes the logout not work?

            Also check to make sure you are confirming that the localStorage has been removed.

    • Drew says:

      Hey Jason, That’s exactly how it would be done. What are the results you’re getting?

      • J says:

        I remove localStorage(facebook_token) as well. Doesn’t alway seem to work though.

        Another thing, when it does work, if I hit back on ChildBrowser, the facebook_token seems to ‘reappear’ and show the authenticated version of my app. This is odd because on logout I check for facebook_token’s value and its null since I removed it; I checked for the facebook_token to make sure the value was there and it was. Is there a better way to clear localStorage than removeItem?

        • Drew says:

          hmm very strange. I do know that when you go back to Facebook you are saying “please authenticate” which it already knows you’re signed in and you’ve given permissions so it just authenticates and sends you back.

          Removing is the best option.. you could change the value to “” for the Facebook_token…

          • J says:

            Hey Drew,

            Still working thru the logout piece. Figured out that localStorage is overwriting values for some weird reason, though the variables have different names.

            Anyway, quick question. When you speak of implementing the Logout by just doing a localStorage.removeItem(facebook_token), where in your code are you placing that, and how do you get the app to check for the token again? Another call to app.init()? Let’s just assume we’re using your original code above.

        • Drew says:

          Hi Jason,
          Okay so we are setting the facebook_token in the facebookLocChanged method.

          localStorage.setItem(facebook_token, data.split("=")[1]);

          If you have removed the facebook_token then you should be able to call app.init() and it will check to see if that localStorage item is there if it isn’t then you are technically logged out. and should show the login button!

          • J says:

            Right, that’s essentially what I was thinking. Here’s my modified version of your code:
            var app = {
            //(skipping down..)
            init:function(){
            // First lets check to see if we have a user or not
            if(!localStorage.getItem(facebook_token)){
            $(“#loginArea”).show();
            $(“#status”).hide();

            $(“#login”).click(function(){
            Facebook.init();
            });
            }
            else {
            //(skipping down again..)
            $(“#logout”).click(function(){
            localStorage.removeItem(facebook_token)
            app.init();
            });
            }

            So essentially, I placed the logout code inside the else clause of app’s init function. Is that where you’d put it?

          • Drew says:

            yeah that’s the idea…. is that not working for you?

          • Ghan says:

            Hey Jason and Drew –

            Here’s what works for me:
            logout:function(){
            console.log(“Facebook.logout() init”);
            localStorage.removeItem(facebook_token);
            $.mobile.changePage( “index.html” );
            app.init();
            },

            But, I notice that the next time I click Log In, I go to the childbrowser window, then immediately logs me in and redirects me back. For me, I’d like childbrowser to ask me for my FB credentials again… so for that, I’m wrangling with the window.plugins.childBrowser.LogOut() mention above. Doesn’t seem to work, don’t know why.

            G

          • Ghan says:

            Hi again guys — There is a lingering issue around login/logout… it seems that successive logins/logouts while the app is running doesn’t work too well.
            1. Launch App
            2. Login –> Success
            3. Logout –> Success
            4. Login –> reaches facebook.com/connect/login_success.html?code=
            … but then it’s stuck there.

            Does anyone else see this?

  14. Ghan says:

    Hi Drew — thanks so much! Invaluable guide.

    How would you get a user’s email from Facebook? I’ve added “email” to &scope= in the authorize URL, but I’m not sure how to now retrieve it.

    • Drew says:

      Hi Ghan,
      To get the email you could do a query of ‘me’ as the _fbType and that should return the most basic user information.

  15. Rajesh Jain says:

    Hi

    I used Phonegap 1.4.1, Android and plugged your code. I had to use the ChildBrowser from the phonegap-plugins , else it was throwing some exception.

    Here is what I had to do,

    I had to add the extra piece of code to install the childbrowser because the childbrowser.js in the phonegap-plugins doesn’t have that.

    if(!window.plugins) {
    window.plugins = {};
    }

    window.plugins.childBrowser = new ChildBrowser();
    return window.plugins.childBrowser;
    };

    I am not sure when does the Phone Load gets called, is that a redundant call..

    /**
    * Load ChildBrowser
    */
    PhoneGap.addConstructor(function() {
    PhoneGap.addPlugin(“childBrowser”, new ChildBrowser());
    });

    Secondly, I have the Facebook URL as http://http://….
    but it auto corrects, not sure why there are two https

    I can login, but on successful login it bring me back to the index.html which has the Login Page.

    Can I redirect to another page?

    How do I bring back all the data and show it on the redirected page. Is there an example of that.

    For example on my redirected page, I can show my facebook status.

    I am a newbie and this has been a very helpful tutorial . Thank you Drew.

    regards
    Rajesh

    • Smitha says:

      Hi,

      I am working with Android and phonegap.But I am not able to login.
      Could you please tell me as to where do I add the /**Load ChildBrowser**/ code?
      The init method is invoked but the // Open Child browser and ask for permissions
      doesn’t happen. What could be the error?
      Thanks in advance,
      Smitha

    • Jasa Niklanovic says:

      “I can login, but on successful login it bring me back to the index.html which has the Login Page.”

      I’m also having problems with android implementation of this , did you by any chance figure this out? Can you paste the code?

      Regards, Jasha

  16. Paul says:

    Hey Drew,

    Have you implemented SSO for your Facebook plugin?

    If so, did you use Facebook’s documentation?

    • Drew says:

      Hey Paul,
      I am not using SSO for this, BUT this is why we save the token and ask for offline access is because once signed on you can take actions and never have to sign in again.

      If a user has loged out using your app if they sign in again, because they have already granted permission it will create a new token and resume where it left off not having to ask for permissions again.

      • Paul says:

        Yes, that functionality is definitely working. The user does stay signed in with your script.

        Just wondering if you’d done this, but no worries. The official “Hackbook for iOS”, doesn’t even work when I built it to my iPad.

        I’m going to tinker with the code from the Facebook dev page and if I get it working, I’ll hit you back.

  17. J says:

    Ghan/ Drew,

    (in reply to Ghan’s ‘There is a lingering issue around login/logout… it seems that successive logins/logouts while the app is running doesn’t work too well.’)

    Yep, that’s exactly my problem as well. I can login/out initially, but after that, the app starts acting weird. Glad to know I’m not the only one, but I really wish I knew how to fix.

  18. Prabhjot says:

    I am facing an issue in childBrowser and showWebPage. When I use:
    window.plugins.childBrowser.showWebPage(“http://www.google.com”);
    The childbrowser pops up, but it is just a black screen i.e opening url about:blank. I am using Phonegap 1.2.0 and ios5.

    Initially, childbrowser was not showing up. For that I modified appdelegate.m a bit and replaced :
    – (BOOL)webView:(UIWebView *)theWebView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType: (UIWebViewNavigationType)navigationType
    {
    return [ super webView:theWebView shouldStartLoadWithRequest:request navigationType:navigationType ];
    }

    WITH

    – (BOOL)webView:(UIWebView *)theWebView shouldStartLoadWithRequest:
    (NSURLRequest *)request navigationType:
    (UIWebViewNavigationType)navigationType
    {
    NSURL *url = [request URL];
    if ([[url scheme] isEqualToString:@”gap”] || [url isFileURL]) {
    return [ super webView:theWebView shouldStartLoadWithRequest:request navigationType:navigationType ];
    }
    else {
    ChildBrowserViewController* childBrowser =
    [ [ ChildBrowserViewController alloc ] initWithScale:FALSE ];
    [super.viewController presentModalViewController:childBrowser
    animated:YES ];
    [childBrowser loadURL:[url description]];
    [childBrowser release];
    return NO;
    }
    }

    This worked and I was able to see the childbrowser window. But I am badly stuck now with the issue that i mentioned above i.e opening up of just a blank page in childbrowser.

    Suggestions….

  19. Mark Walls says:

    Hi, I am wondering what version of phonegap that you are using for this? I downloaded the new 1.6 today, and I am having plenty of problems getting this to run. Mostly revolving around header files: PhoneGapViewController.h and PGPlugin.h.

    I saw earlier that you suggested changing the header references. I did that, but it just started flowing errors through the entire document.

    Is it possible to perhaps give a second document to all the changes that are above to match with your current GIT repository and tell what version of Cordova you are operating with?

    Thank you for all your work on this. It is absolutely awesome of you. It is insane that FB hasn’t dealt with this issue yet, even if it is really Cordova’s issue. You would think someone at FB would be interested in people creating apps that lead to involvement with their content. :)

    • Drew says:

      Hi Mark,
      Yes I should really update all the documentation for this. This project was built with phonegap 1.3 so it’s very out of date.

      A couple suggestions, if you create a new project in phonegap, download the newest childbrowser – I recently pushed the changes to the phonegap Plugins git. After that the implementation is actually pretty similar to what this one is doing. I will push an update soon for this project!

  20. ben says:

    Hi,

    I have followed the tutorial but seem to be getting an error when I build:

    PGPlugin.h not found.

    Can’t seem to find the file anywhere.

    If anyone could help me it would be a big help.

    Thanks!

    • Drew says:

      Based on the error you’re getting I am assuming you’re using cordova, make sure you’re using the newest ChildBrowser. This project was created in phonegap 1.2 so it’s a bit outdated.

      I am working on doing an updated version for Cordova, but I am a bit busy with work so it’s on my list of things to do.

  21. Pelle says:

    Hey Drew,

    thanks a lot for this great article. Helped me a lot getting ChildBrowser.js and Cordova finally working. Also managed to change the return URL of the PG Facebook Connect Plugin and now I can login to FB with my app. Only problem now is that as soon as I’m logged in, I get errors. This part here seems to be the problem:

    FB.fbConnect.restoreLastSession();
    var session = FB.fbConnect.session;
    if (session && session.expires > new Date().valueOf()) {
    FB.Auth.setSession(session, ‘connected’);
    }

    Console says: [INFO] Init error: TypeError: ‘undefined’ is not a function

    It seems, the method setSession() is somehow messed up…

    So after logging in, I can’t use any FB functionality. Any suggestions?

    I’m on Cordova 1.7, XCode 4.2.1 and the latest versions of PG FB Connect and Childbrowser.js.

    THANKS!

  22. Joris Meeuwsen says:

    Hi Drew,
    Can you use this project only in Xcode or also in Dreamweaver?
    I’m working in Dreamweaver on Windows working with the Phonegap functions and let Phonegap generate the apps for various platforms.
    If it is not possible in Dreamweaver, does somebody know a way to integrate with Facebook and Twitter?
    Thanks!
    Joris

    • Drew says:

      Hi Joris,
      I am not sure if Phonegap build supports childbrowser.. if it does then you are good to go and everything should work as needed!

  23. Is anyone else getting a blank/white page after logging in to Facebook??

    Please told me how to solve this problem

    • Drew says:

      Hi Binaya,
      Yes you will get a white screen that says “success” on it. That is the redirect URL from Facebook. You need to be sure to have the location change function that catches this and grabs the access token.

      Also Facebook has made some major changes to using the method we use here in regards to the offline_access – I am currently working on a new project that will get around this issue.

      • Hi Drew,

        Exactly i got white screen that says “success” on it.Kindly gave me solution as soon as possible.thanks

        • Richie says:

          Drew, the success.html screen (requiring that the “done” be clicked) is a bit of a sticking point. Is there are a way to simply to back to the app once it is done? Can it be tricked into going pass that.

          Alternatively is there a way to do something funky (and old) like a response.redirect (but to where?)

          -R

          • Drew says:

            Hey Richie, in the onLocation change function the childbrowser should close if the credentials check out and all worked out.

            One note – on android it seems to sometimes get caught up if you add

            fbCode = fbCode.replace("#_=_","");
            

            for some reason it gets that #_=_ appended to the end of the token, remove that and all should be good.

  24. Andrew Barker says:

    Hi,

    This tutorial is superb. I have tried it and got two simple issues:

    Where should I get “PGPlugin.h” and “ChildBrowserViewController.h”? The IDE is complaining that it can’t find them and yet I don’t know how I should get them.

    Newbie to iOS programming so excuse my stupidity! Got everything else up to this point working fine :)

    Thanks

    Andrew

    • Drew says:

      Make sure you have added the childbrowser plugin to your xcode project. Depending on your version of phonegap, this was made for 1.4 and lower, but if you are using the most recent version just download the newest release of the childbrowser.

  25. Pete Field says:

    Hey Drew, awesome work on this plugin, just spent two days trying to figure out why it worked in the simulator and not on the device. As you mentioned on June 21st, it appears that build.phonegap does not support childbrowser.

    Hopefully this saves somebody else the time it took me. You have to build the IPA from xcode

    Cheers,
    Pete

  26. If you’re stuck in a loop where the ajax call doesn’t succeed e.g. The ChildBrowser closes and you see the login page, check line 50 and ensure that each http:// in that string is https:// and you should be good to go.

    This was found using Cordova 1.6.0 using the latest ChildBrowser plugin.

  27. Theodore says:

    Hello drew, thanks once more
    I hace a strange issue
    As i ‘m clicking the button I am getting a black screen and this error

    The view controller returned NO from -shouldAutorotateToInterfaceOrientation: for all interface orientations. It should support at least one orientation.

    I can’t even open other urls, any ideas?

  28. Jasa Niklanovic says:

    Hello Drew,

    do you by any chance have any experience in making your Twitter and Facebook apps work in phone gap/android? Regards, Jasa

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>