Wednesday, November 4, 2009

Get Facebook user's permission

In using the Facebook developer toolkit it was necessary to ask the user for extended permission to publish to their wall server side.

The FbPermissions class is initialized with the required permissions. Calling the GetPermissionFromUser will display the facebook permissions dialog.

If all permissions were granted the dialog will not be invoked next time. This prevents a momentary flash of the permissions dialog if you're using AJAX to make server requests.


<script type="text/javascript">
function FbPermissions(options){
 this.requiredPermissions = options["RequiredPermissions"]; 
}

FbPermissions.prototype.callback = function(e, successCallback, failureCallback){
 if(e === false){
  if(failureCallback != null)
   failureCallback();
 }
 else if(e == null || e === ""){
  if(failureCallback != null)
   failureCallback();
 }
 else{
  if(successCallback != null)
   successCallback();
  
  //Simple length check should be sufficient 
  if(this.requiredPermissions.split(',').length == e.split(',').length)
   this.requiredPermissions = "";
 }  
}

FbPermissions.prototype.GetPermissionFromUser = function(successCallback, failureCallback)
{
 var me = this;
 if(this.requiredPermissions != null && this.requiredPermissions.length != 0)
  FB.Connect.showPermissionDialog(this.requiredPermissions, function(e){me.callback(e, successCallback, failureCallback);});
 else
  successCallback();    
}


Usage


Using the class is simple. Just initialize the FbPermissions with the required permissions using a server side script block. Then invoke the GetPermissionFromUser function with a success and failure callback method.

var permissions = new FbPermissions({RequiredPermissions : '<%= Model.RequiredFacebookPermissions %>'});

function PostToWall(message) {
   permissions.GetPermissionFromUser(
   function(){/*Call your facebook application here*/},
   function(){alert('You must grant permission');})  
  }
</script>

<a href="#" onclick="PostToWall('hi'); return false;">click me</a>

No comments:

Post a Comment