Well, you found your answer. The HTA context is in another working directory from the script package context. You must have a batch of script cd or pushd up to "%~dp0" . This is pretty standard for batch scripts added to context menus, etc.
s.WriteLine('pushd "%~dp0"');
... as you have already done, this is the right decision. You must also
s.WriteLine('@echo off & setlocal');
... to limit the amount of variables in this batch script for the runtime of the batch script itself.
But the main reason I'm posting an answer is to provide more information about the Chakra engine. Even with IE9, 10, 11, Edge, no matter what is installed, the Windows script Host supports a feature set as it existed in JScript 5.7. According to the MSDN documentation :
Starting with JScript 5.8, by default, the JScript scripting engine supports a set of language functions as it existed in version 5.7. This should maintain compatibility with earlier versions of the engine. To use the full language feature set in version 5.8, the Windows script host interface must call IActiveScriptProperty :: SetProperty .
What does this mean if you want to use methods in JScript 5.8 or later (for example, JSON, Object.keys , Array.prototype.forEach() methods, etc.), you basically need to write your own Windows script Host interpreter. But with HTA there is a simple hack that will allow you to use the features of IE9. Just add the following line to the top of your HTA file:
<meta http-equiv="x-ua-compatible" content="IE=9" />
Before:
<script> function get() { try { var json = JSON.parse(document.getElementById('json').value); alert(json.var1); } catch(e) { alert(e.message); } } </script> <textarea id="json">{"var1": "It works!"}</textarea> <button onclick="get()">Go!</button>
Output:
'JSON' - undefined
After:
<meta http-equiv="x-ua-compatible" content="IE=9" /> <script> function get() { try { var json = JSON.parse(document.getElementById('json').value); alert(json.var1); } catch(e) { alert(e.message); } } </script> <textarea id="json">{"var1": "It works!"}</textarea> <button onclick="get()">Go!</button>
Output:
It works!
However, this hack is not limited to HTA. You can also make it work on the JScript and JScript.NET console by creating a htmlfile COM object, entering the <meta> tag in it, and then copying the newly opened methods and objects to the current script host.