CreateTextFile not working when hta is set to open as notepad by default (javascripting)

孤人 提交于 2019-12-01 09:22:28

问题


I'm getting this really weird problem when I try to create a text file using javascripting and a hta file.

This is the code broken down to its basics:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Untitled Document</title>
<script>

alert("creating file");
var fso = new ActiveXObject("Scripting.FileSystemObject");
var s = fso.CreateTextFile("test.txt", true);
s.WriteLine("it works");
s.Close();
alert("file created");
</script>
</head>

<body>
</body>
</html>

This is in a hta file called "Untitled.hta" As long as I set the Open With > Choose Default Program to "Microsoft (R) HTML Application Host" and then open the hta file the text file gets created just fine.

But if I set Open With > Choose Default Program to "Notepad" and then Open With "Microsoft (R) HTML Application Host" the text file doesn't get created.

Does anyone know why this is happening? It normally wouldn't matter but if a client has hta files set to open as notepad by default then my hta file wont work as intended.

To complicate things further replace

var s = fso.CreateTextFile("test.txt", true);

with

var s = fso.CreateTextFile("TestFolder/test.txt", true);

and where the hta file is located create a folder called "TestFolder"

If you do the same thing as you did before, having it set to Notepad as default gives the Path not found error (but it works fine if the default is set to Microsoft (R) HTML Application Host)


回答1:


That happens because you are using a relative path. Put this snippet before creating a FSO:

var shell = new ActiveXObject("WScript.Shell");
alert(shell.currentDirectory);

Probably your HTA alerts C:\Windows\System32 (depended on the used OS). This is the folder, where you can find test.txt. Also "Path not found" error is now explained...

To fix the issue, use absolute paths only, or set the current directory:

shell.currentDirectory = 'C:/Some_Path';


来源:https://stackoverflow.com/questions/14742435/createtextfile-not-working-when-hta-is-set-to-open-as-notepad-by-default-javasc

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!