Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

I was wondering how I would get the name of the current user in JavaScript as part of an HTML document.

In Java, one would type System.getProperty("user.name"); to achieve this. What is the alternative to this in JavaScript?

like image 487
Dylan Wheeler Avatar asked Mar 01 '12 14:03

Dylan Wheeler


People also ask

How do I find system user?

In the box, type cmd and press Enter. The command prompt window will appear. Type whoami and press Enter. Your current user name will be displayed.

How do I get users in HTML?

Using HTML forms, you can easily take user input. The <form> tag is used to get user input, by adding the form elements. Different types of form elements include text input, radio button input, submit button, etc. Let's learn about the <input> tag, which helps you to take user input using the type attribute.

How do I find my Windows browser Username?

you can do it w/ very small java applet that has to signed you just need System. getProperty("user.name") The solution will work on any browser supporting java.


2 Answers

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.

like image 63
Surreal Dreams Avatar answered Sep 20 '22 17:09

Surreal Dreams


There is no fully compatible alternative in JavaScript as it posses an unsafe security issue to allow client-side code to become aware of the logged in user.

That said, the following code would allow you to get the logged in username, but it will only work on Windows, and only within Internet Explorer, as it makes use of ActiveX. Also Internet Explorer will most likely display a popup alerting you to the potential security problems associated with using this code, which won't exactly help usability.

<!doctype html> <html> <head>     <title>Windows Username</title> </head> <body> <script type="text/javascript">     var WinNetwork = new ActiveXObject("WScript.Network");     alert(WinNetwork.UserName);  </script> </body> </html> 

As Surreal Dreams suggested you could use AJAX to call a server-side method that serves back the username, or render the HTML with a hidden input with a value of the logged in user, for e.g.

(ASP.NET MVC 3 syntax)

<input id="username" type="hidden" value="@User.Identity.Name" /> 
like image 45
Greg Avatar answered Sep 23 '22 17:09

Greg