How to Get the Name of the Current Windows User in JavaScript

How to get the name of the current Windows user in JavaScript

JavaScript runs in the context of the current HTML document, so it won't be able to determine anything about a current user unless it's in the current page or you do AJAX calls to a server-side script to get more information.

JavaScript will not be able to determine your Windows user name.

getting windows username with javascript

The solution I found for getting the username sent to the server was:

string winlogon = Request.ServerVariables["LOGON_USER"];

After enabled Windows Authentication Mode in IIS.

Get first and last name on Windows with Electron

I found a way to do it,

  1. I am using the username package to obtain the logged-in user.

async getUsername() {
return await username();
}

  1. Then in node js and electron you can use the child processes, child_process docs.

  2. When you perform the command net user <username> or net user <username> / domain you get all the user information, among all the information is the full name, also the name can be empty.


const child = require('child_process');
let exec = child.exec;

// And make a function for do command

function execute(command, callback){
exec(command, function(error, stdout, stderr){
let result = null;

if(!error){

var splitted = stdout.split("\n");
var username = '';
var fullname = '';

for(var i=0; i < splitted.length; i++){
if(splitted[i].search("User name") != -1){
splitted[i] = splitted[i].replace('User name',' ');
splitted[i] = splitted[i].trim();
username = splitted[i];
}else if(splitted[i].search("Full Name") != -1){
splitted[i] = splitted[i].replace('Full Name',' ');
splitted[i] = splitted[i].trim();
fullname = splitted[i];
}
}

let data = {
username: (username) ? username.toLowerCase() : null,
fullname: (fullname) ? fullname: null
}

result = data;
} else{
result = null;
}
callback(result);
});
};

This way you can get the user's full name.

Get Microsoft Account Name in MS Edge in JavaScript

As this was intended for an ASP.NET application, I managed to achieve what I wanted (aka getting the Windows Username) using Windows Authentification based on a few other articles that I'll link below, I hope this helps anybody who is facing similiar issues:

  • https://forums.asp.net/t/2044520.aspx?Add+Windows+Authentication+to+Mvc+5+project
  • How do I get the currently loggedin Windows account from an ASP.NET page?
  • https://forums.asp.net/t/1598421.aspx?Getting+windows+username+using+windows+authentication

There are fairly more answers in other Stack Overflow questions as well, but this is mainly what I used (Note: One thing that took me hours is that Visual Studio didn't update the project properties to also work with Windows Authentification, so be sure to check this as well)



Related Topics



Leave a reply



Submit