Given below are the steps to get Current User Id.
- Create SharePoint Hosted App project.
- Write code to get the Current User Id in App.js file.
Here, we are going to display user id in alert message. Based on your project requirement, you can use this User Id value in your project.
Step 1 - Create SharePoint Hosted App project.
- Set scope of the Site Collection and set permissions as "FullControl".
Step 2 - Write the code to get current User Id in App.js file.
Open the App.js file, remove the existing code, and paste the below code.
- 'use strict';
- var hostweburl;
- var appweburl;
- var context = SP.ClientContext.get_current();
- var user = context.get_web().get_currentUser();
-
-
- $(document).ready(function() {
-
- hostweburl = decodeURIComponent(getQueryStringParameter("SPHostUrl"));
- appweburl = decodeURIComponent(getQueryStringParameter("SPAppWebUrl"));
- var scriptbase = hostweburl + "/_layouts/15/";
- getCurrentUserREST();
- });
-
- function getQueryStringParameter(paramToRetrieve) {
- var params = document.URL.split("?")[1].split("&");
- for (var i = 0; i < params.length; i = i + 1) {
- var singleParam = params[i].split("=");
- if (singleParam[0] == paramToRetrieve) return singleParam[1];
- }
- }
-
- function getCurrentUserREST() {
- $.ajax({
- url: appweburl + "/_api/web/currentUser",
- method: "GET",
- headers: {
- "Accept": "application/json; odata=verbose"
- },
- success: function(data) {
- var UserId = data.d.Id;
- alert("Current User Id= " + UserId);
- },
- error: function(data) {}
- });
- }
- After "Trusting" the app, it will display the current User Id in alert message, whenever the page is reloaded.
That's it. Please send your feedback in comments section.