Need private packages and team management tools?Check out npm Teams »

powertoast

1.1.3 • Public • Published

About

Windows toast notification using PowerShell for NodeJS, electron or NW.js (Windows 8, 8.1, 10).
Inspired by go-toast

Doesn't use any native module. Everything is done through PowerShell but you can use native WinRT API instead by optionally installing NodeRT relative package :

  • @nodert-win10-rs4/windows.data.xml.dom
  • @nodert-win10-rs4/windows.ui.notifications

This will give you a little boost as you'll not have to wait for PowerShell to start.

Looking for Windows balloon notification ? node-powerballoon

Example

//Sending a simple notification
const toast = require('powertoast');
 
toast({
  title: "NPM",
  message: "Installed.",
  icon: "https://static.npmjs.com/7a7ffabbd910fc60161bc04f2cee4160.png"
}).catch((err) => { 
  console.error(err);
});

Installation

npm install powertoast

Optional packages

Prequisites: VS2017 / Python 2.7(node-gyp) / Windows SDK 10.0.17134.0 (1803 Redstone 4)

Options

⚠️ Windows 8/8.1 have very basic notification compared to Windows 10, some options will be ignored.
Windows 7 and before don't have toast notification and thus will throw the error Unsupported Windows version.

📖 Microsoft Toast API.
📖 Toast content XML schema.

  • disableWinRT

    If you have installed the optional NodeRT native module but for whatever reason(s) you want to use PowerShell instead. Then set this to true

  • appID

    Your Application User Model ID.

    Default to Microsoft Store so you can see how it works if not specified.

    ⚠️ An invalid appID will result in the notification not being displayed !

    You can view all installed appID via the powershell command :

    PS> Get-StartApps %search%
    
    const toast = require('powertoast');
     
    toast({
      appID: "Microsoft.XboxApp_8wekyb3d8bbwe!Microsoft.XboxApp", //Xbox App
      title: "Hello",
      message: "world"
    }).catch(err => console.error(err));
     

    ### If you are using this module with electron : In Electron, you can set it at runtime using the app.setAppUserModelId() method.

    Example with a dev electron app : (Dont forget to add a non-pinned shortcut to your start menu in this case.)

    const toast = require('powertoast');
     
    toast({
      appID: "D:\\dev\\hello_world\\node_modules\\electron\\dist\\electron.exe", //app.setAppUserModelId(process.execPath) 
      title: "Hello",
      message: "world"
    }).catch(err => console.error(err));
     
  • title

    The title of your notification

  • message

    The content message of your notification. You can use "\n" to create a new line for the forthcoming text.

    Since the Windows 10 Anniversary Update the default and maximum is up to 2 lines of text for the title, and up to 4 lines (combined) for the message.

  • attribution //Windows 10 Anniversary Update

    Reference the source of your content. This text is always displayed at the bottom of your notification, along with your app's identity or the notification's timestamp.

    On older versions of Windows that don't support attribution text, the text will simply be displayed as another text element (assuming you don't already have the maximum of 3 text elements).

  
  const toast = require('powertoast');
 
  toast({
    appID: "com.squirrel.GitHubDesktop.GitHubDesktop",
    title: "Github",
    message: "Someone commented your issue",
    icon: "D:\\Desktop\\25231.png",
    attribution: "Via Web"
  }).catch(err => console.error(err));
 
  • icon

    The URI of the image source, using one of these protocol handlers:

    1. If you are using a UWP appID you can use:
    • http:// or https://
    • ms-appx:///
    • ms-appdata:///local/
    1. If you are using a Win32 appID you can use:
    • file:/// (eg: "D:\\Desktop\\test.jpg")

    The Icon should be an absolute path to the icon (as the toast is invoked from a temporary path on the user's system, not the working directory).

    Icon dimensions are 48x48 pixels at 100% scaling.

    .png and .jpeg are supported.

    For http and https remote web images, there are limits on the file size of each individual image.
    3 MB on normal connections and 1 MB on metered connections.
    Before Fall Creators Update, images were always limited to 200 KB.

    If an image exceeds the file size, or fails to download, or times out, or is an unvalid format the image will be dropped and the rest of the notification will be displayed.

  • cropIcon

    You can use this to 'circle-crop' your image (true). Otherwise, the image is square (false).

    default to false.

  • headerImg //Anniversary Update

    Display a prominently image within the toast banner and inside the Action Center if there is enough room.
    Image dimensions are 364x180 pixels at 100% scaling. If the image is too big it will be cut from the bottom.

    Otherwise same restriction as above.

  • footerImg (inline-image)

    A full-width inline-image that appears at the bottom of the toast and inside the Action Center if there is enough room. Image will be resized to fit inside the toast.

    Otherwise same restriction as above.

  • silent

    True to mute the sound; false to allow the toast notification sound to play. Default to false.

  • audio

    The audio source to play when the toast is shown to the user.
    You can't use file:/// with this ! You are limited to the Windows sound schema available in your system.

    example: ms-winsoundevent:Notification.Default

    Tip: But you can create your own Windows sound schema with the registry and use it for your toast:

    File must be a .wav, by default Windows sounds are located in %WINDIR%\media

    //Registry
    Windows Registry Editor Version 5.00
    
    [HKEY_CURRENT_USER\AppEvents\Schemes\Apps\.Default\**YOUR_SOUND_ID**]
    
    [HKEY_CURRENT_USER\AppEvents\Schemes\Apps\.Default\**YOUR_SOUND_ID**\.Current]
    @="path_to_your_sound_file.wav"
    
    [HKEY_CURRENT_USER\AppEvents\Schemes\Apps\.Default\**YOUR_SOUND_ID**\.Default]
    @="path_to_your_sound_file.wav"
    
    //Js
    const toast = require('powertoast');
    
    toast({
      appID: "com.squirrel.GitHubDesktop.GitHubDesktop",
      title: "Github",
      message: "Someone commented your issue",
      audio: "ms-winsoundevent:**YOUR_SOUND_ID**"
    }).catch(err => console.error(err));
    
  • longTime

    Increase the time the toast should show up for.
    Default to false.

    Most of the time "short" (default) is the most appropriate, and Microsoft recommends not using "long".
    This is only here for specific scenarios and app compatibility (Windows 8).

    Long is around ~ 25sec
    Short is the user defined value (Windows settings > Ease of Access > Display > Show notification for ...)

    Or registry: HKCU\Control Panel\Accessibility -> MessageDuration::DWORD (Not recommended)

    User value default to 5sec; Available: 5,7,15,30,1min,5min

  • onClick

    Protocol to launch when the user click on the toast.
    If none (default) click will just dismiss the notification.

    Only protocol type action buttons are supported as there's no way of receiving feedback from the user's choice.
    (Well except if you are using NodeRT native module but I didn't implement it to match PowerShell features 😛)

    Example of protocol type action button to open up Windows 10's maps app with a pre-populated search field set to "sushi":

    const toast = require('powertoast');
     
    toast({
      message: "Sushi",
      onClick: "bingmaps:?q=sushi"
    }).catch(err => console.error(err));

    You can also redirect to an http/https resource :

    const toast = require('powertoast');
     
    toast({
     message: "Google It",
     onClick: "https://www.google.com"
    }).catch(err => console.error(err));

    Tip: You can create your own protocol: create your own URI scheme.
    And even send args back to your electron app:
    In electron just make your app a single instance with app.requestSingleInstanceLock()
    Then use the second-instance event to parse the new args.

    Let's say we created an electron: URI scheme; Let's send a notification:

    toast({
      message: "custom URI",
      onClick: "electron:helloworld"
    }).catch(err => console.error(err));

    In electron:

    if (app.requestSingleInstanceLock() !== true) { app.quit(); }
    app.on('second-instance', (event, argv, cwd) => {  
      
      console.log(argv);
      //[...,"electron:helloworld"]
     
    }) 
  • button

    Array of buttons to add to your toast. You can only have up to 5 buttons.
    After the 5th they will be ignored.

    [{text: "", onClick: ""}, ...]
    

 
const toast = require('powertoast');
 
toast({
 title: "Browser",
 message: "Choose your favorite",
 button: [
   {text: "Firefox", onClick:"https://www.mozilla.org/en/firefox/new/"},
   {text: "Chrome", onClick:"https://www.google.com/chrome/"}
 ]
}).catch(err => console.error(err));
 
  • scenario

    "default", "alarm", "reminder", "incomingCall"
    Default to ... well, 'default'.

    The scenario adjusts a few behaviors:

    • Reminder: The notification will stay on screen until the user dismisses it or takes action (Sticky notification). Microsoft doesn't recommend to use this just for keeping your notification persistent on screen.
    • Alarm: In addition to the reminder behaviors, alarms will additionally loop audio with a default alarm sound.
    • IncomingCall: Same behaviors as alarms except they use ringtone audio and their buttons are styled differently (displayed full screen on Windows Mobile devices).
      When using Reminder or Alarm, you must provide at least one button on your toast notification.
      Otherwise, the toast will be treated as a normal toast.
  • progress //Creators Update

    Add a progress bar to your toast.

    {
      header : optional string,
      footer: optional string,
      percent : percent of the progress bar, set it to null to get a progress with the little dots moving,
      custom : optional string to be displayed instead of the default percentage string
    }
    

 
const toast = require('powertoast');
 
toast({
title: "Dummy",
message: "Hello World",
icon: "https://steamcdn-a.akamaihd.net/steamcommunity/public/images/apps/480/winner.jpg",
progress:{
  header: "Header",
  footer: "Footer",
  percent: 50,
  custom: "10/20 Beers"
}
}).catch(err => console.error(err));
 
  • uniqueID

    You can replace a notification by sending a new toast with the same uniqueID.
    This is useful when using a progress bar or correcting/updating the information on a toast.
    And you don't want to end up with a flood of similar toasts in the Action Center.

    However this is not really suitable for information that frequently changes in a short period of time (like a download progress for example) or subtle changes to your toast content, like changing 50% to 65%.

  • sequenceNumber

    Provide sequence number to prevent out-of-order updates, or assign 0 to indicate "always update".
    A higher sequence number indicates a newer toast.
    default to 0

    The sequence number may helps to ensure that toasts will not be displayed in a manner that may confuse when updating/correcting.

  • group //Creators Update

    You can group notifications under a common header within Action Center

    {
    id: use the same header id string to unify them under the header,
    title: title of the header, title can be different and will be shown above the toast.
           title from the most recent notification within a group is used in Action Center, 
           if that notification gets removed, then the title falls back 
           to the next most recent notification. 
    }
    

  • timeStamp

    Unix epoch time in seconds.
    Current time by default if not specified.

    By default, the timestamp visible within Action Center is set to the time that the notification was sent.
    You can optionally override the timestamp with your own custom date and time, so that the timestamp represents the time the message/information/content was actually created, rather than the time that the notification was sent.
    This also ensures that your notifications appear in the correct order within Action Center (which are sorted by time). Microsoft recommends that most apps specify a custom timestamp.
    But you can safely omit this option.

Common Issues

  • I dont see any notification

    1. Check your appID.
    2. Check your focus assistant and notifcation settings. Don't forget 'Quiet hours' on Windows 8.1
    3. In some cases you need a shortcut (win8) or a non-pinned shortcut (win10) to your start menu for the specified appID.
  • Where is my icon/image ?

    Check url or path (should be an absolute path as the toast is invoked from a temporary path on the user's system, not the working directory).
    If an image exceeds the file size, or fails to download, or times out, or is an unvalid format the image will be dropped and the rest of the notification will be displayed.

  • Notifications when app is fullscreen aren't displayed

    You can't drawn a notification over an exclusive fullscreen app.
    But you can over a fullscreen borderless.

    Double check your focus assistant and notifcation settings in the windows settings panel.
    Note that since Windows 10 1903 there is a new default fullscreen auto rule enabled to alarm only by default which will prevent toast notification over fullscreen borderless.

  • Slight delay between event and the display of the notification

    Running the PowerShell script can take a few seconds in some cases.
    If it really bothers you, you might want to try to use the optional NodeRT native module.
    If you are loading a remote img resource via http/https it can significantly impact the delay if it hasn't been cached yet by Windows.

  • Notification don't stay in the Action center

    When using a Win32 appID notification will remove itself from the Action center when the app gets focus.
    Use a UWP appID instead.

Known missing features

  • Expiration time
  • Supress toast : send directly to Action Center
  • Adaptative progress bar update
  • Context menu button
  • Action(OnClick,OnDismiss)/button js callback (Already explained why in this doc)

Install

npm i powertoast

DownloadsWeekly Downloads

0

Version

1.1.3

License

MIT

Unpacked Size

28.6 kB

Total Files

5

Last publish

Collaborators

  • avatar