Skip to content

Windows toast notification and toastXml string builder

License

Notifications You must be signed in to change notification settings

xan105/node-powertoast

Folders and files

NameName
Last commit message
Last commit date

Latest commit

ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 

Repository files navigation

About

Windows toast notification and toastXml string builder.

Doesn't use any native module. Everything is done through PowerShell but you can use native WinRT API bindings instead by optionally installing NodeRT relative packages (see installation for more details).

Please note that when using PowerShell some features such as click events and user input requires Powershell โ‰ฅ 7.1 (pwsh) also known as PowerShell Core.
Using WinRT (NodeRT) is a bit faster as you don't have to wait for the PowerShell VM to start.

Electron

Powertoast was made for Node.js first but it also works in Electron with either PowerShell or WinRT (NodeRT).
If you prefer to use the new Electron native API directly. You can easily build a toastXml string for it.

Example

A simple toast

import { Toast } from "powertoast";

//Create a toast
const toast = new Toast({
  title: "NPM",
  message: "Installed.",
  icon: "https://static.npmjs.com/7a7ffabbd910fc60161bc04f2cee4160.png"
})

//Events (optional)
toast.on("activated", (event, input) => { 
  // Where event and input are the data from an interactive toast
  console.log("click");
});
toast.on("dismissed", (reason) => { console.log(reason) });

toast.show() //Promise
.then(()=>{
  console.log("Sent");
})
.catch((err) => { 
  console.error(err);
});

Build a toastXml string for Electron native API:

//Main process
import { Notification } from "electron";
import { toXmlString } from "powertoast";
  
const options = {
  title: "First partner",
  message: "Every journey begins with a choice",
  button: [
    { text: "Bulbasaur", activation: "myapp:green" },
    { text: "Charmander", activation: "myapp:red" },
    { text: "Squirtle", activation: "myapp:blue" }
  ]
};

const xmlString = toXmlString(options);
const toast = new Notification({ toastXml: xmlString });
toast.show();

Installation

npm install powertoast
Optional NodeRT packages

All NodeRT scopes up to the latest official @nodert-win10-rs4 and unofficial made by the community up to @nodert-win11-22h2 are supported. The Windows SDK version they target is implied in their name.

๐Ÿ’ก Mixing NodeRT modules from different scopes is supported (priority to the most recent SDK) but should be treated with caution.

NodeRT modules required for toast notification:

  • windows.data.xml.dom
  • windows.ui.notifications

For user input (text box and dropdown selection list) you will also need:

  • windows.ui.notifications (> nodert-win10-rs4 (1803) since it's available on win10 โ‰ฅ 1903)
  • windows.foundation
  • windows.foundation.collections

๐Ÿ’ก If you have trouble compiling NodeRT native addons.
They are available precompiled through the @xan105/nodert package.

npm i @xan105/nodert --modules="windows.ui.notifications, windows.data.xml.dom, windows.foundation, windows.foundation.collections"

Note that you can also add a list of modules in your package.json file under the _nodert/modules path:

"_nodert" : {
  "modules" : [
    "windows.data.xml.dom",
    "windows.ui.notifications"
  ]
},

Please see @xan105/nodert for more details.

Electron

For Electron add the --electron flag to target Electron's ABI

npm i @xan105/nodert --electron --modules="windows.ui.notifications, windows.data.xml.dom"

โš ๏ธ Electron โ‰ฅ 14 : NodeRT should be loaded in the main process NodeRT#158

API

โš ๏ธ This module is only available as an ECMAScript module (ESM) starting with version 2.0.0.
Previous version(s) are CommonJS (CJS) with an ESM wrapper.

โ„น๏ธ Windows 8/8.1 support was removed in 3.x

Named export

Toast(option?: object): Class

Create a toast notification.

extends ๐Ÿ“– EventEmitter

Constructor

(option?: object)

โ„น๏ธ Because there is a ton of options for toast notification, they are in TOAST.md.

Events

  • activated (event: string, input: { key: value, ... })

    When user activates a toast notification through a click.

    Event is the argument passed by the notification or button.

    Input (textbox and/or selection) is the user input represented as key/value pair(s).

  • dismissed (reason: string)

    When a toast notification leaves the screen, either by expiring or being explicitly dismissed by the user.

    Name Description
    UserCanceled User dismissed the toast
    ApplicationHidden Application explicitly hid the toast
    TimedOut Toast had been shown for the maximum allowed time and was faded out

Methods

  • clear(): Promise<void>

    Remove the notification from the notification center and all event listeners.

  • show(option?: object): Promise<void>

    Show toast notification.

    โš™๏ธ Options

    • disableWinRT?: boolean (false)

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

    • disablePowershellCore?: boolean (false)

      By default when using PowerShell this module will first try to use pwsh (PowerShell Core), then powershell (PowerShell Desktop / Windows Embedded). Set this to true to skip pwsh and only use powershell which is included with Windows.

      โ„น๏ธ PowerShell Core has some caveats hence the option to disable/skip it:

      • It's painfully slow to start.
      • It needs to be installed and its path added to your env var.
      • In order for PowerShell Core to use WinRT it will have to download WinRT assemblies through its package manager (done on first run).

      โš ๏ธ Please note that some features such as click events and user input requires Powershell โ‰ฅ 7.1 (pwsh).

    • keepalive?: number (6) seconds

      โš ๏ธ This option is only for when listening for events !

      The maximum amount of time PowerShell will wait for events before exiting or how long to keep the event loop alive for NodeRT.

      PowerShell needs to be running to subscribe to the events and NodeRT registered event listener does not keep the event loop alive. The default value is 6 seconds as 5 seconds is the default notification duration but keep in mind some users might have change this value in their Windows settings.

      โ„น๏ธ NB: When using NodeRT If you have something else maintaining the event loop then you can ignore this.

    Returns

    โœ”๏ธ Resolves as soon as the notification has been dispatched. Except when PowerShell needs to be running to subscribe to events in which case the promise will resolve only afterwards.

    โŒ Rejects on error.

toXmlString(option?: object): string

Expose the toastXML string builder used by the Toast class for debugging purposes or for example if you want to use it with Electron native API.

Please see the Toast class constructor for the relevant options.

โ„น๏ธ The following options have no effect when just building a Toast XmlString:

  • aumid
  • uniqueID
  • hide
  • sequenceNumber
  • expiration

const isWinRTAvailable: boolean

True if the peerDependencies for WinRT were successfully loaded; false otherwise.

remove(aumid: string, uniqueID?: string | string[]): Promise<void>

Remove programmatically notification(s) from the notification center.

If using only aumid then it removes every notification for said aumid in the notification center.
If you provide an optional uniqueID (string) then it removes that specific notification for the given aumid.

โ„น๏ธ This library uniqueID option actually sets both tag and groupLabel to the same value for convenience.
If you want to use the tag and groupLabel properties of a toast to target a notification then use
uniqueID (array) as [ groupLabel: string, tag?: string ].

getHistory(aumid: string, verbose?: boolean): Promise<object[]>

List the current notification(s) for the given aumid in the notification center.

Return an array of object with the following properties:
name type description
expirationTime string time after which a toast should not be displayed (eg: "01/08/2021 20:53:23 +07:00")
tag string unique identifier (tag)
group string unique identifier (group label)

If verbose (false) is set to true then the following properties are added:

name type description
remoteID string or null id to correlate this notification with another one generated on another device
suppressPopup boolean whether toast's pop-up UI is displayed on the user's screen
mirroringAllowed boolean whether notification is allowed to be displayed on multiple devices
expiresOnReboot boolean whether toast will remain in the notification center after a reboot
highPriority boolean whether the notification is displayed in high priority (wake up the screen, etc)
status string or null additional information about the status of the toast

๐Ÿ“– Microsoft doc

๐Ÿ“– Microsoft Toast API.
๐Ÿ“– Toast content XML schema.
๐Ÿ“– ToastNotificationHistory class.
๐Ÿ“– ToastNotification properties.
๐Ÿ“– send-local-toast-other-apps.