Showing posts with label JavaScript. Show all posts
Showing posts with label JavaScript. Show all posts

Friday, 22 May 2015

Using IFrame and postMessage to perform cross page communication

This is a JavaScript function which wraps all the necessary logic to communicate with a target page, below are the key points of this implementation:
  1. target page is loaded using an hidden iframe
  2. once iframe finishes loading, send data over via postMessage
  3. register a function to wait for and respond to message to be received from target page only once
  4. async operation has been wrapped with a jQuery promise
function sendAndReceiveMessage(targetUrl, targetOrigin, dataToSend){
 //Utility routine to generate a unique id
 function createGuid()
 {
     return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function(c) {
         var r = Math.random()*16|0, v = c === 'x' ? r : (r&0x3|0x8);
         return v.toString(16);
     });
 }

 var deferred = $.Deferred();

 var iframeID = createGuid();
 var iframe = $("<iframe></iframe>", {
           "src": targetUrl,
           "id": iframeID,
           "style": "display:none;"
          });
 $("body").append(iframe);
 
 iframe.one("load", function(){
  var childFrame =  $("#"+iframeID)[0];
  childFrame.contentWindow.postMessage(JSON.stringify(dataToSend), targetOrigin);
 });

 $(window).on("message", handleMessage);

 function handleMessage(event){
  $(window).off("message", handleMessage);
  var dataReceived = JSON.parse(event.originalEvent.data);
  $("#"+iframeID).remove();
  deferred.resolve(dataReceived);
 }

 return deferred.promise();
}


 
Usage example:

  $("#btnTest").click(function(){
   var dataSend = {"value": 123};
   sendAndReceiveMessage("child.html", "*", dataSend).done(function(data){
    alert("Test result: " +data.value);
   });
  });


A sample implementation of child.html is below. In this case I just double the value received from calling page and return it back.


(function(){
 function receiveMessage(event){
  var data = JSON.parse(event.data);
  data.value *= 2;
  event.source.postMessage(JSON.stringify(data), "*");
 }

 $(document).ready(function(){
  window.addEventListener("message", receiveMessage, false);        
 });

})();

Thursday, 29 November 2012

Add/Remove/Check Current User Against a Specific Group

//Check if current user is in a specific group
function isCurrentUserInGroup(groupId, funUserInGroup, funUserNotInGroup, funOnError) {
    var ctx = new SP.ClientContext.get_current();
    var currentUser = ctx.get_web().get_currentUser();
    ctx.load(currentUser, 'Id', 'LoginName');
    var group = ctx.get_web().get_siteGroups().getById(groupId);
    var users = group.get_users();
    ctx.load(users);
 
    ctx.executeQueryAsync(function (sender, args) {
        //See whether the user exists
        var userFound = false;
        var userEnumerator = users.getEnumerator();
        while (userEnumerator.moveNext() && !userFound) {
            var user = userEnumerator.get_current();
            if (user.get_id() == currentUser.get_id()) {
                //User exists in the group
                userFound = true;
                if (funUserInGroup != null)
                    funUserInGroup();
            }
        }
        //User doesn't exist in the group
        if (!userFound && (funUserNotInGroup != null))
            funUserNotInGroup();
 
    }, function (sender, args) {
        if (funOnError != null)
            funOnError(sender, args);
    });
}
 
//Add current user to specific group
function addCurrentUserToGroup(groupId, funOnSuccess, funOnError) {
    var ctx = new SP.ClientContext.get_current();
    var currentUser = ctx.get_web().get_currentUser();
    ctx.load(currentUser);
    var group = ctx.get_web().get_siteGroups().getById(groupId);
    ctx.load(group);
    group.get_users().addUser(currentUser);
 
    ctx.executeQueryAsync(function (sender, args) {
        if (funOnSuccess != null)
            funOnSuccess(sender, args);
    }, function (sender, args) {
        if (funOnError != null)
            funOnError(sender, args);
    });
}
 
//Remove current user from specific group
function removeCurrentUserFromGroup(groupId, funOnSuccess, funOnError) {
    var ctx = new SP.ClientContext.get_current();
    var currentUser = ctx.get_web().get_currentUser();
    ctx.load(currentUser);
    var group = ctx.get_web().get_siteGroups().getById(groupId);
    ctx.load(group);
    group.get_users().remove(currentUser);
 
    ctx.executeQueryAsync(function (sender, args) {
        if (funOnSuccess != null)
            funOnSuccess(sender, args);
    }, function (sender, args) {
        if (funOnError != null)
            funOnError(sender, args);
    });
}
 

Wednesday, 31 October 2012

How to Write a jQuery Plugin

It is actually pretty simple, you just have to follow a basic template. Here I am showing you how to build one to change elements to a round shape. Please note that because I use border radius here in the example you need IE9+ to view the result.

(function ($) {
    //This is where you define your plugin name, in this case - makeMeRound
    $.fn.makeMeRound = function (options) {

        //Extend default settings with options passed through paramete
        var settings = $.extend({
            //Below are default settings, can be overridden by parameter
            'border_color': 'red',
            'border_width': '2px'
        }, options);

        //Wrapped in a each loop in case jQuery selector returns a collection of elements
        //We return this here to maintain chainability during method calls
        return this.each(function () {
            //Below is the core of the plugin
            var max = $(this).width() > $(this).height() ? $(this).width() : $(this).height();
            $(this).css('width', max).css('height', max).css('border-color', settings.border_color).css('border-width', settings.border_width).css('border-radius', '50% 50% 50% 50%');
        });

    };

})(jQuery); //To make sure that your plugin doesn't collide with other libraries that might use the dollar sign
 
//Calling plugin
$(document).ready(function () {
    $('input').makeMeRound(); //use default setting
    $('img').makeMeRound({ 'border_width': '2px' }); //specify custom setting
});

The above script operating on the html below

<input type="button" value="Click Me" style="border-width:1px;width:100px;height:25px;"/>
<img border="1px" src="http://www.tutordoctor.com/sites/default/files/Halloween.jpg" />

will produce the following result
 
 

Friday, 19 October 2012

How To Check Whether Current User Belongs To A Certain Group Using JavaScript

Using JavaScript Client Object Model:
 
function isCurrentUserInGroup(groupName, functionUserInGroup, functionUserNotInGroup, functionGroupNotFound, functionOnError) {
    var ctx = new SP.ClientContext.get_current();
    //Get info of current user
    var currentUser = ctx.get_web().get_currentUser();
    ctx.load(currentUser, 'Id', 'LoginName');
    //Retrieve all site groups
    var groups = ctx.get_web().get_siteGroups();
    ctx.load(groups);
 
    ctx.executeQueryAsync(function (sender, args) {
        //See whether the group exists
        var groupFound = false;
        var groupEnumerator = groups.getEnumerator();
        while (groupEnumerator.moveNext() && !groupFound) {
            var group = groupEnumerator.get_current();
            if (group.get_title() == groupName) {
                //Found the group, now try to load users of this group
                groupFound = true;
                var users = group.get_users();
                ctx.load(users);
                ctx.executeQueryAsync(function (sender, args) {
                    //See whether the user exists
                    var userFound = false;
                    var userEnumerator = users.getEnumerator();
                    while (userEnumerator.moveNext() && !userFound) {
                        var user = userEnumerator.get_current();
                        if (user.get_id() == currentUser.get_id()) {
                            //User exists in the group
                            userFound = true;
 
                            if (functionUserInGroup != null)
                                functionUserInGroup();
                        }
                    }
 
                    //User doesn't exist in the group
                    if (!userFound && (functionUserNotInGroup != null))
                        functionUserNotInGroup();
 
                }, function (sender, args) {
                    if (functionOnError != null)
                        functionOnError(sender, args);
 
                });
            }
        }
 
        //Group doesn't exist
        if (!groupFound && (functionGroupNotFound != null))
            functionGroupNotFound();
 
    }, function (sender, args) {
        if (functionOnError != null)
            functionOnError(sender, args);
 
    })
 
}
 
// Sample usage 
ExecuteOrDelayUntilScriptLoaded(function () {
    isCurrentUserInGroup('Approvers',
                         function () {
                            alert('User is in the group.');
                         },
                         function () {
                            alert('User is NOT in the group.');
                         },
                         function () {
                             alert('Group does NOT exist.');
                         },
                         function (sender, args) {
                             alert('Request failed.' + args.get_message() + '\n' + args.get_stackTrace());
                         });
}, "sp.js");