JavaScript - How to get the name of the current user

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(""); to achieve this. What is the alternative to this 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.


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>
    <title>Windows Username</title>
<script type="text/javascript">
    var WinNetwork = new ActiveXObject("WScript.Network");

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 the script is running on Microsoft Windows in an HTA or similar, you can do this:

var wshshell=new ActiveXObject("");
var username=wshshell.ExpandEnvironmentStrings("%username%");

Otherwise, as others have pointed out, you're out of luck. This is considered to be private information and is not provided by the browser to the javascript engine.


I think is not possible to do that. It would be a huge security risk if a browser access to that kind of personal information


Working for me on IE:

<script type="text/javascript">
  var WinNetwork = new ActiveXObject("WScript.Network");

...but ActiveX controls needs to be on in security settings.


Recent Questions

Top Questions

Home Tags Terms of Service Privacy Policy DMCA Contact Us

©2020 All rights reserved.