1

I want to use *.js file both: on local web page on my pc (as JavaScript) and as WSH JScript when I double click *.js file. Is it possible to write a code running on both platforms?

How to check is running JS file is JavaScript or Microsoft JScript?

I tried this, but it doesn't work:

if (typeof(document) == "undefined")
    alert('WSH Script!');
    WScript.Quit;
}
else {
    document.writeln('Hello world');
}
Tom
  • 23
  • 7
  • Welcome to StackOverflow! How does the script you included fail? (Please edit your question to include any error messages or describe any incorrect behaviour.) I'm not familiar with WSH, but according to [this question](https://stackoverflow.com/q/14450424/1175455) the `window` object isn't present in the WSH environment, so you might try checking for that. – Harry Cutts Aug 13 '18 at 19:38
  • My code returns this error: `--------------------------- Windows Script Host --------------------------- Script: D:\JS\plik js - oryg.js Line: 4 Char: 1 Error: Syntax error Code: 800A03EA Source: Microsoft JScript compilation error` I'm wondering is there something like `tepeof` in JScript? Because it seams to be a problem... – Tom Aug 14 '18 at 08:08

3 Answers3

2
  1. You can check if WScript object exists e.g

    if (typeof WScript === 'object')

  2. Quit is a function so you should call it, e.g

    WScript.Quit();

Sergii Vorobei
  • 1,477
  • 13
  • 19
  • Thank you for your response. Good point with WScript.Quit();. alert() is also not recognized on JScript so I changed it Now I changed the code to: `if (typeof WScript === 'object') { WSHshell= WScript.CreateObject("WScript.Shell") WSHshell.Popup("WSH Script!") WScript.Quit(); } else { document.writeln('Hello world'); }` Now it runs as JScript very well, and on a web browser! Thank you very much! – Tom Aug 14 '18 at 08:40
1

I'm posting the right code (thanks to Sergii Vorobei):

if (typeof WScript === 'object') {
    WSHshell= WScript.CreateObject("WScript.Shell")
    WSHshell.Popup("WSH Script!")
    WScript.Quit();
}
else {
    document.writeln('Hello world');
}
Tom
  • 23
  • 7
1

another nice trick using "conditional compilation":

if (/*@cc_on !@*/0) {
    WScript.StdOut.WriteLine("Hello from JScript");
} else {
    console.log('Hello from NodeJS');
}

more info here.

Foad S. Farimani
  • 12,396
  • 15
  • 78
  • 193