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?
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.
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.
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.
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.
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" />
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With