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');
}
2
  • 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 the window object isn't present in the WSH environment, so you might try checking for that. Commented Aug 13, 2018 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
    Commented Aug 14, 2018 at 8:08

3 Answers 3

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();

1
  • 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
    Commented Aug 14, 2018 at 8: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');
}
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.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.