javascript 在 html 中使用 windows 用户名

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/20768185/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-27 19:15:04  来源:igfitidea点击:

Use windows username in html

javascripthtmlvariablesdesktop

提问by user3133613

I was experimenting with using a .htm file as a desktop background and i wanted to make it so it would say something like "Welcome, 'username'!" where 'username' would be my username that i use to log on to my computer. I have a windows xp computer if that makes a difference. I do not have much experience with javascript, but with some searching i think i found something to use to get the username:

我正在尝试使用 .htm 文件作为桌面背景,我想让它看起来像“欢迎,'用户名'!” 其中“用户名”是我用来登录计算机的用户名。如果这有所作为,我有一台 Windows XP 计算机。我对javascript没有太多经验,但是通过一些搜索,我想我找到了一些可以用来获取用户名的东西:

<script language="javascript">
function GetUserName()
{
    var wshell = new ActiveXObject("WScript.Shell");
    alert(wshell.ExpandEnvironmentStrings("%USERNAME%"));
}
</script>

I just found that on the web, i am not sure which part is the acquired username... What i need is to use this later in my html to display on my wallpaper: "Welcome, 'username'!" I am not sure if it is needed, but i will include it anyways, the html code i want the welcome statement would be in

我刚刚在网上发现,我不确定哪一部分是获取的用户名......我需要稍后在我的 html 中使用它来显示在我的壁纸上:“欢迎,'用户名'!” 我不确定是否需要它,但无论如何我都会包含它,我希望欢迎声明的 html 代码将在

<center><div class="widget"><div class="title"> *welcome statement here* </div></div></center>

Alright thanks guys!!

好的谢谢各位!!

回答by Barmar

Give your title DIV an ID:

给你的标题 DIV 一个 ID:

<center><div class="widget"><div class="title" id="welcome"> Welcome </div></div></center>

Then use the following Javascript:

然后使用以下 Javascript:

window.addEventListener('load', function() {
    var username = GetUserName();
    document.getElementById('welcome').innerHTML = 'Welcome, '+username;
});

function GetUserName() {
    var wshell = ActiveXObject && new ActiveXObject("WScript.Shell");
    return wshell && wshell.ExpandEnvironmentStrings("%USERNAME%");
}