Search code examples
javascriptwindowswindows-10jscriptwsh

How do you do an alert / message / popup box using JScript on Windows?


I'm trying to do a Window alert on Windows 10 and it's not going so well.

This is what I tried:

window.alert("Alert");

And

alert("Alert");

It doesn't matter if its in another language too. But if there is a way to do it in JavaScript, please answer!


Solution

  • window.alert is the browser function only. You can execute it in browser environment only.

    For simple message box in WSH JScript write:

    WScript.Echo("Windows message box sample");
    

    If you need extended message box in WSH JScript write:

    var mbOK = 0,
        mbOKCancel = 1,
        mbCancel = 2,
        mbInformation = 64, // Information icon
        text  = //"Windows Script Host sample",
        title = //"Title sample",
        wshShell = WScript.CreateObject("WScript.Shell"),
        intDoIt =  wshShell.Popup(text,
                        0, //if > 0, seconds to show popup. With 0 it is without timeout.
                        title,
                        mbOKCancel + mbInformation);
    if(intDoIt == mbCancel) 
    {
        WScript.Quit(); //End of WScript (every for & while loops end too)
    }
    
    WScript.Echo("Sample executed");
    

    You have to save all it in example.js file and execute this file with mouse double click. If you need support for internationale messages then save it in unicode format (but NOT in UTF-8 format!).

    Some useful exended example

    If you need some message box every 15 seconds (or maybe 1 hour) you can do it with while loop and WScript.sleep function, because we don't have setTimeout function in WSH JScript too.

    In the next code sample we have a message box every 15 seconds in endless loop if you click all the time on OK button. A click on cancel button will end the full script (every for & while loops end too).

    while(true)
    {
        var mbOK = 0,
            mbOKCancel = 1,
            mbCancel = 2,
            mbInformation = 64, // Information icon
            text  = "TO-DO: Write your App code! Do It! Just Do It!",
            title = "Simple TO-DO thing",
            wshShell = WScript.CreateObject("WScript.Shell"),
            intDoIt =  wshShell.Popup(text,
                            0, //if > 0, seconds to show popup. With 0 it is without timeout.
                            title,
                            mbOKCancel + mbInformation);
        if(intDoIt == mbCancel) 
        {
            WScript.Quit(); //End of WScript (every for & while loops end too)
        }
    
        WScript.sleep(15000); //Every 15 seconds. And 60*60*1000=3600000 for every hour
    }
    

    More information you will get in Microsoft Windows Script Host 2.0 Developer's Guide online book.