I’m making a simple reading canvas app, and I want to be ale to check if the user has been logged in before loading any of the content/articles. Naturally I have the FB.Init method, and I have a getLoginStatus within it, and it looks like this (I’ve removed my namespace and ID):
<script>
window.fbAsyncInit = function() {
FB.init(
{
appId : '[APP ID]', // App ID
status : true, // check login status
cookie : true, // enable cookies to allow the server to access the session
xfbml : true // parse XFBML
});
FB.getLoginStatus(function(response) {
if (!response.authResponse) {
var oauth_url = 'http://www.facebook.com/dialog/oauth/';
oauth_url += '?client_id=[APP ID]';
oauth_url += '&redirect_uri=' + encodeURIComponent('http://apps.facebook.com/[APP NAMESPACE]/');
oauth_url += '&scope=read_stream,publish_stream,offline_access'
window.top.location = oauth_url;
}
});
};
// 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>
But it no matter what I do, it loads my HTML content first (my Articles, Divs, Paragrafs, texts…) and redirects after finishing with that.
The script is the head od my HTML. I’ve also tried loading it through a onLoad() method in the body, but that didn’t work either, it still loads some of my HTML content before redirecting.
How can I make it checked if the user is logged in to Facebook (and redirect if he’s not), before loading even a single letter or image of the HTML code?
You are using asynchronous loading of the facebook js sdk, and more than that, once you send the output back from the server (being static content or dynamic content) the browser gets the entire content and loads it, there’s no much you can do about that.
If you want to check if the user is authenticated before then I advice you to use the Server-Side auth flow.
That way you can know the status before you even return the content to the user, if you discover that he’s not authenticated then the content you send back to him is the redirection content.
Only when the user comes back authenticated will you send back the canvas content.
Edit
If your entire app is static then keep it that way, no need to add php (or any other server side solution) just for server-side authentication.
I’m not exactly sure why you mind if the page is loaded before the redirect, here are two “solutions”:
(1) Load a minimized page that has just the fb sdk and methods for checking if the user is logged in or not, if he is not then redirect him.
If he is logged in then load a script that adds the rest of the content and dynamically add it to the dom.
(2) In case that you just don’t want the user to see something before he logs in, just make that part hidden with css and when he logs in change it using javasript.