Add Read Permission To User And Stop The Permission Inheritance In SharePoint2013 List Using JavaScript Object Model

In this blog, we will see about how to add a read permission for the user and stop the inherit permissions in the list , using JavaScript Object Model. Using this code, we can break the security inheritance of a Website, list, library, or list item through the BreakRoleInheritance method. When we want to grant an access to the folders or the documents or simply for an item to a specific user, we go ahead and break the Inheritance and provide an access to the specified user.

Add JavaScript files given below in to your solution.
  1. <script type="text/javascript" src="../Scripts/jquery-1.9.1.min.js"></script>  
  2. <script type="text/ecmascript" src="../_layouts/SP.core.debug.js" />  
  3. <script type="text/ecmascript" src="../_layouts/SP.runtime.debug.js" />  
  4. <script type="text/ecmascript" src="../_layouts/SP.debug.js" />  
The blog given below shows how to break the security of a list by using the breakRoleInheritance(copyRoleAssignments, clearSubscopes) function of the List object. 
  1. <script type="text/ecmascript">  
  2.     function readPermisiontoUSER() {  
  3.         var Context = new SP.ClientContext.get_current();  
  4.         var Website = Context.get_web();  
  5.         var oList = Website.get_lists().getByTitle('CustomList');  
  6.   
  7.     var ListItem = oList.get_items().getById('4');  
  8.   
  9.     ListItem.breakRoleInheritance(false);  
  10.     this.User = Context.get_web().get_siteUsers().getByLoginName('SPDEV\\gowtham');  
  11.   var collRoleDefinitionBinding = SP.RoleDefinitionBindingCollection.newObject(Context);  
  12.     collRoleDefinitionBinding.add(Context.get_web().get_roleDefinitions().getByType(SP.RoleType.reader));  
  13.     oListItem.get_roleAssignments().add(User, collRoleDefinitionBinding);  
  14.     Context.load(User);  
  15.     Context.load(ListItem);  
  16.     Context.executeQueryAsync(Function.createDelegate(thisthis.onQuerySucceeded), Function.createDelegate(thisthis.onQueryFailed));  
  17. }  
  18.   
  19. function onQuerySucceeded(sender, args) {  
  20.   
  21.     alert('Role inheritance broken for item ');  
  22.         
  23. }  
  24.   
  25. function onQueryFailed(sender, args) {  
  26.   
  27.     alert('Request failed. ' + args.get_message() + '\n' + args.get_stackTrace());  
  28. }  
  29. </script>   
Thanks for reading my blog. 
X

Build smarter apps with Machine Learning, Bots, Cognitive Services - Start free.

Start Learning Now