ECMA Script : To Add current logged in user to SharePoint group 2013/ 2010
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<script type="text/ecmascript">
ExecuteOrDelayUntilScriptLoaded(init,'sp.js');
var currentUser;
var currentUserName;
var currentUserEmail;
var currentUserLogin;
var siteUrl = '/';
function init(){
var clientContext = new SP.ClientContext.get_current();
var oWeb= clientContext.get_web();
currentUser = oWeb.get_currentUser();
clientContext.load(currentUser);
clientContext.executeQueryAsync(Function.createDelegate(this,this.onQueryUNSucceeded), Function.createDelegate(this,this.onQueryUNFailed));
}
function onQueryUNSucceeded() {
currentUserName = currentUser.get_title();
currentUserLogin= currentUser.get_loginName();
currentUserEmail= currentUser.get_email();
document.getElementById('txtUserName').innerHTML = currentUserName;
document.getElementById('txtloginName').innerHTML = currentUserLogin;
document.getElementById('txtEmail').innerHTML = currentUserEmail;
}
function onQueryUNFailed(sender, args) {
alert('Request failed. \nError: ' + args.get_message() + '\nStackTrace: ' + args.get_stackTrace());
}
function addUserToSharePointGroup() {
var clientContext = new SP.ClientContext(siteUrl);
var collGroup = clientContext.get_web().get_siteGroups();
var oGroup = collGroup.getById(7);
var userCreationInfo = new SP.UserCreationInformation();
userCreationInfo.set_email(currentUserEmail);
userCreationInfo.set_loginName(currentUserLogin);
userCreationInfo.set_title(currentUserName);
this.oUser = oGroup.get_users().add(userCreationInfo);
clientContext.load(oUser);
clientContext.executeQueryAsync(Function.createDelegate(this, this.onQuerySucceeded), Function.createDelegate(this, this.onQueryFailed));
}
function onQuerySucceeded() {
alert(this.oUser.get_title() + " added.");
}
function onQueryFailed(sender, args) {
alert('Request failed. ' + args.get_message() + '\n' + args.get_stackTrace());
}
</script>
</head>
<body>
<div id="txtUserName"></div><br>
<div id="txtloginName"></div><br />
<div id="txtEmail"></div><br />
<input id="submitBtn" onclick="addUserToSharePointGroup()" type="button" value="Add User To Group"/>
</body>
</html>