electron-windows-notifications

repository·master·Indexed 42 days ago

https://github.com/felixrieseberg/electron-windows-notifications

A library for creating native Windows toast and tile notifications in Electron applications using WinRT bindings via NodeRT. Supports Windows 8, 8.1, and 10. It provides classes for ToastNotification, TileNotification, and SecondaryTile, allowing developers to use XML templates with printf-style string replacement for dynamic content. Version 3.0.8.

Tokens
4.9K
Snippets
18
Records
20
Agent score
53%

What's inside electron-windows-notifications

  1. Configure appUserModelId

    master

    The appUserModelId identifies your application in Windows.

    • In Electron: You can set this at runtime using app.setAppUserModelId().
    • In this module: If you do not pass appId to the notification constructor, the module assumes it is a global property on Electron's main thread.
    • Recommendation: Unless running inside a UWP container, you should explicitly pass the appId to the constructor.
  2. Use printf-style string replacement in templates

    master

    The module uses util.format to perform printf-like string replacement within your XML templates. Placeholders in the template string are replaced by values provided in the strings array.

    Supported Placeholders:

    • %s: String
    • %d: Number (integer or float)
    • %j: JSON
    • %%: A single percent sign (%)

    Important: If a placeholder does not have a corresponding argument in the strings array, it will not be replaced. To avoid XML syntax errors, always use the strings property for dynamic content to ensure proper XML escaping.

  3. Install and run the electron-windows-notifications sample

    master

    To set up and run the Electron sample application, navigate to the sample directory, install dependencies, and rebuild the native modules for the Electron version used in the app. Finally, start the application using npm.

    Note: The rebuild command assumes a Windows environment using the local electron-rebuild binary.

    cd samples\electron
    npm install
    .\node_modules\.bin\electron-rebuild -m .\app\node_modules
    npm start
  4. Use electron-windows-notifications for Windows toast and tile notifications

    master

    The electron-windows-notifications library provides an interface for sending Windows Toast notifications and Tile notifications.

    Platform Compatibility: This library is designed specifically for Windows. If run on a non-Windows platform or an unsupported Windows version (versions other than 8, 8.1, or 10.0), the library exports 'no-op' (no-operation) versions of its classes and methods. These no-ops prevent the application from crashing but will not trigger any actual notifications.

    Supported Windows Versions:

    • Windows 10 (10.0)
    • Windows 8.1 (8.1)
    • Windows 8 (8)
    const notifications = require('electron-windows-notifications');
    
    // On supported Windows versions, you can access:
    // notifications.getToastNotifier()
    // notifications.TileNotification
    // notifications.history
    // etc.
  5. Create a TileNotification

    master

    Use the TileNotification class to update the app's primary or secondary tiles. This requires the app to be running inside the UWP model (Windows 10 Anniversary Update and later).

    Note: For UWP support in Electron, see electron-windows-store.

    The constructor accepts an options object with the following properties:

    • template (string): The XML template for the notification.
    • strings (string[]): An array of strings used to replace placeholders in the template.
    • tag (string): Unique identifier of this notification within the notification group.
    • tileId (string): If set, the specific tile will be updated. Otherwise, the app's primary tile is used.
    // Note: The README provides a ToastNotification example for TileNotification usage.
    // Ensure you are running in a UWP container for tile updates to work.
  6. Create a ToastNotification

    master

    Use the ToastNotification class to create pop-up toast notifications. The constructor accepts an options object with the following properties:

    • template (string): The XML template for the notification. You can use new Template() to customize XML based on defaults.
    • strings (string[]): An array of strings used to replace placeholders in the template. XML escaping is applied automatically.
    • expirationTime (Date): The time after which the notification should not be displayed.
    • group (string): Group identifier for the notification.
    • tag (string): Unique identifier of this notification within the notification group.
    • appId (string): The appUserModelId of the application. If not provided, it defaults to the global property in Electron's main thread.
    const appId = 'electron-windows-notifications'
    const {ToastNotification} = require('electron-windows-notifications')
    
    let notification = new ToastNotification({
        appId: appId,
        template: `<toast><visual><binding template="ToastText01"><text id="1">%s</text></binding></visual></toast>`,`
        strings: ['Hi!']
    })
    
    notification.on('activated', () => console.log('Activated!'))
    notification.show()
  7. Create secondary tile notifications with SecondaryTile

    master

    The SecondaryTile class allows you to create and manage secondary tiles for the Windows Start screen. These tiles can be pinned by the user and, when clicked, pass specific arguments back to your application.

    Constructor Options

    OptionTypeDescription
    tileIdstringA unique identifier (max 64 chars). Must start with a letter or number and contain only a-z, A-Z, 0-9, ., or _. Providing an existing ID overwrites the previous tile.
    displayNamestringThe name displayed on the tile, in tooltips, and in search results.
    argumentsstringAn app-defined string passed back to your app when the tile is activated. Truncated at 2048 characters.
    desiredSizestringThe size of the tile. Valid values: Default, Square150x150, or Wide310x150.
    logostringA URI string for the tile's logo.
    visualElementsObjectAn object where keys are visual element names and values are URI strings (e.g., background images).

    Instance Methods

    • requestCreate(): Returns a Promise that resolves when the tile has been successfully requested for creation on the Windows Start screen.
    const SecondaryTile = require('electron-windows-notifications').SecondaryTile;
    
    const tile = new SecondaryTile({
      tileId: 'my_unique_tile_01',
      displayName: 'My App Tile',
      arguments: 'action=open_settings',
      desiredSize: 'Wide310x150',
      logo: 'https://example.com/logo.png',
      visualElements: {
        backgroundImage: 'https://example.com/background.png'
      }
    });
    
    tile.requestCreate()
      .then(() => console.log('Tile created successfully'))
      .catch(err => console.error('Failed to create tile:', err));
  8. Find existing secondary tiles

    master

    The SecondaryTile class provides static methods to retrieve existing tiles currently pinned to the Start screen.

    • SecondaryTile.findAll(): Returns a Promise that resolves with an array of all secondary tiles found on the system.
    • SecondaryTile.findAllForPackage(): Returns a Promise that resolves with an array of all secondary tiles belonging specifically to your application's package.
    const SecondaryTile = require('electron-windows-notifications').SecondaryTile;
    
    // Find all tiles for your specific app package
    SecondaryTile.findAllForPackage()
      .then(tiles => {
        console.log('Existing tiles for this app:', tiles);
      })
      .catch(err => {
        console.error('Error finding tiles:', err);
      });
  9. Enable notification queuing for tiles

    master

    You can enable the notification queue, which allows the tile to queue up to five notifications. This can be enabled globally for all tile sizes or specifically for certain dimensions.

    Available methods:

    • enableNotificationQueue(value): Enables queuing for all tile sizes. Defaults to true.
    • enableNotificationQueueForSquare150x150(value): Enables queuing specifically for the medium tile. Defaults to true.
    • enableNotificationQueueForSquare310x310(value): Enables queuing specifically for the large tile. Defaults to true.
    • enableNotificationQueueForWide310x150(value): Enables queuing specifically for the wide tile. Defaults to true.
    const updater = new TileUpdater();
    
    // Enable queuing for all sizes
    updater.enableNotificationQueue(true);
    
    // Or specifically for a size
    updater.enableNotificationQueueForSquare310x310(true);
  10. Create toast notifications with ToastNotification

    master

    The ToastNotification class allows you to create Windows toast notifications using an XML template and a list of strings. It extends EventEmitter, allowing you to listen for user interactions like activated or dismissed events.

    Constructor Options

    When instantiating new ToastNotification(options), you can provide the following:

    OptionTypeDescription
    templatestringAn XML template string containing placeholders (e.g., %s) for the provided strings.
    stringsstring[]An array of strings that will be sanitized, XML-escaped, and injected into the template placeholders.
    expirationTimeDateThe time at which the notification should expire.
    groupstringA group identifier for the notification.
    tagstringA tag identifier for the notification.
    appIdstringThe Application User Model ID (AUMID). If not provided, it defaults to the value returned by getAppId().

    Events

    • activated: Emitted when the user interacts with the notification. The event payload contains the arguments from the ToastActivatedEventArgs.
    • dismissed: Emitted when the notification is dismissed.
    • failed: Emitted if the notification cannot be shown due to system settings (e.g., disabled by Group Policy or App Manifest).
    const ToastNotification = require('electron-windows-notifications').ToastNotification;
    
    const notification = new ToastNotification({
      template: '<toast><visual><binding template="ToastGeneric">%s</binding></visual></toast>',
      strings: ['Hello World!'],
      appId: 'YOUR_APP_ID'
    });
    
    notification.on('activated', (t, args) => {
      console.log('Notification activated with args:', args);
    });
    
    notification.show();
  11. Show and hide toast notifications

    master

    Once a ToastNotification instance is created, use the following methods to control its visibility:

    • show(): Displays the notification. This method performs a check against Windows notification settings (via checkSettings()) before attempting to show the toast. If notifications are disabled by the manifest, group policy, user settings, or application settings, the failed event will be emitted.
    • hide(): Hides the currently active toast notification.
    const notification = new ToastNotification({
      template: '<toast><visual><binding template="ToastGeneric">%s</binding></visual></toast>',
      strings: ['Message text']
    });
    
    // Display the notification
    notification.show();
    
    // Hide the notification
    notification.hide();