Break Item Level Permission Using Javascript/JSOM

Sometimes, we get certain requirements to change the permission of the item; i.e., the item should only be visible to certain groups or members.
 
Thus, here I am going to share a method to break item level inheritance, using JSOM.
  1. //Params:context - Clientcontext.  
  2. //itemId -ID of item.  
  3. //person1 - people picker which accepts only a single user.  
  4. //person2 - people picker which accepts multiple users.   
  5.   
  6. function BreakSecurityInheritanceAddUser(context, itemId, person1, person2) {  
  7.             var oList = context.get_web().get_lists().getByTitle(<List Name>);  
  8.             var web = context.get_web();  
  9.             var groupNames = web.get_siteGroups();  
  10.             var ownerName = "";  
  11.             var membername = "";  
  12.             var oListItem = oList.getItemById(itemId);  
  13.             oListItem.breakRoleInheritance(false);  
  14. //This copies only the role of currently logged in user & deletes/does not copy remaining roles.  
  15. //if u set it to true it will copy all the roles and u need to delete them manually.  
  16.             context.load(groupNames);  
  17.             context.executeQueryAsync(function () {  
  18.           var groupEnum = groupNames.getEnumerator();  
  19.      while (groupEnum.moveNext())   
  20.      var grpItem = groupEnum.get_current();  
  21.      context.load(grpItem);  
  22.                     if (grpItem.get_title() == "* Owners") ownerName = grpItem;  
  23.                     if (grpItem.get_title() == "* Members") membername = grpItem;  
  24.                 }  
  25.          if (person1 != null && person1 != "undefined" && person1 != "")  
  26.                     var p1 = web.ensureUser(person1);  
  27.                     var p2 = [];  
  28.                     if (person2 != null && person2 != "undefined" && person2 != "") {  
  29.                     for (var i = 0; i < rdrAccess.length; i++) {  
  30.                         p2[i] = web.ensureUser(person2[i]);  
  31.                     }  
  32.                 }  
  33.                 var readerRoleDefinitionBinding = SP.RoleDefinitionBindingCollection.newObject(context);  
  34.                 readerRoleDefinitionBinding.add(context.get_web().get_roleDefinitions().getByType(SP.RoleType.reader));  
  35.                 if (person2 != null && person2 != "undefined" && person2 != "") {  
  36.                     for (var i = 0; i < person2.length; i++) {  
  37.                         if (p2[i] != null) oListItem.get_roleAssignments().add(readerAccess[i], readerRoleDefinitionBinding);  
  38.                         context.load(p2[i]);  
  39.                     }  
  40.                 }  
  41.                 var editRoleDefinitionBinding = SP.RoleDefinitionBindingCollection.newObject(context);  
  42.                 editRoleDefinitionBinding.add(context.get_web().get_roleDefinitions().getByType(SP.RoleType.editor));  
  43.                 if (p1 != null) { oListItem.get_roleAssignments().add(assigne, editRoleDefinitionBinding); context.load(p1); }  
  44.                if (membername != null) { oListItem.get_roleAssignments().add(membername, editRoleDefinitionBinding); context.load(membername); }  
  45.                var adminRoleDefinitionBinding = SP.RoleDefinitionBindingCollection.newObject(context);  
  46.                 adminRoleDefinitionBinding.add(context.get_web().get_roleDefinitions().getByType(SP.RoleType.administrator));  
  47.                 if (ownerName != null) { oListItem.get_roleAssignments().add(ownerName, adminRoleDefinitionBinding); context.load(ownerName); }  
  48.                 context.load(oListItem);  
  49.                 context.executeQueryAsync(  
  50.                                function () {  
  51.                                    console.log('Success');  
  52.                                    window.location.href = <redirect to allitems page.>;  
  53.                                },  
  54.                                function (sender, args) {  
  55.                                    console.log(args.get_message());  
  56.                                    window.location.href =  <redirect to allitems page.>;;  
  57.                                });  
  58.             }, function (sender, args) {  
  59.                 alert(args.get_message());  
  60.                 window.location.href =  <redirect to allitems page.>;  
  61.             });  
  62. }  
The code, given above, runs fine, when you create the item, as the item has not inherited the permission of the list.
 
Whenever you are editing the already created item, the code, given above, won’t work.
 
Since it has already inherited the permission of the list and at that time, you need to copy all the roles and delete the specific roles, which you want to delete. The code, given below, can be referenced-
  1. function BreakSecurityInheritanceAddUser(context, itemId) {  
  2.             var oList = context.get_web().get_lists().getByTitle(<List name>);  
  3.             var web = context.get_web();  
  4.             var groupNames = web.get_siteGroups();//I need to assign item to cretain groups so fetching the groups  
  5.             var oListItem = oList.getItemById(itemId); // to get item by itemId  
  6.             oListItem.breakRoleInheritance(true);  
  7.      //if u set it to false it will copy all the roles and u need to delete them manually.  
  8.             var perms = oListItem.get_roleAssignments();   
  9. /*Get the RoleAssignments collection for the item */  
  10.             context.load(perms);  
  11.             context.load(groupNames);  
  12.             context.executeQueryAsync(  
  13.             function () {  
  14.                 var groupEnum = groupNames.getEnumerator();  
  15.                 while (groupEnum.moveNext()) {  
  16.                    var grpItem = groupEnum.get_current();  
  17.                    context.load(grpItem);  
  18.                     if (grpItem.get_title() == "* Owners") ownerName = grpItem;  
  19.                     if (grpItem.get_title() == "* members") members = grpItem;  
  20.                 }  
  21.                 var RoleAssignments = [];   
  22. /*Create an array to store the role assignments so we can delete them later */  
  23.                 var permEnumerator = perms.getEnumerator();  
  24.                 while (permEnumerator.moveNext()) { /*Loop through each role assignment... */  
  25.                     RoleAssignments.push(permEnumerator.get_current()); /*Add it to our array */  
  26.                 }  
  27.                                   
  28. breakinheritance(true)   
  29. //use below code to delete the users .make sure u dont delete the current user.else u will be given access denied when u call execute query  
  30.                 var count = RoleAssignments.length;  
  31.                 for (var i = 0; i < count; i++) {   
  32. /*Loop through our array and tell each RoleAssignment to delete itself */  
  33.                     RoleAssignments[i].deleteObject(); }                 
  34.                 context.executeQueryAsync(function () {                   
  35.                    //Perform Role assignments as above.       
  36.      context.executeQueryAsync(  
  37.                                    function () {  
  38.                                        //alert("Success");  
  39.                                        console.log('Success');  
  40.                                        window.location.href = <redirect URL>;  
  41.                                    },  
  42.                                    function (sender, args) {  
  43.                                        console.log(args.get_message());  
  44.                                    });  
  45.                 }, function () { }); /*Execute our client side commands */  
  46.             }, function (sender, args) { /*Show an error message if something went wrong */  
  47.                 alert(args.get_message());  
  48.             }  
  49.             );  
  50. }