notification.ts 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687
  1. // Copyright 2019-2021 Tauri Programme within The Commons Conservancy
  2. // SPDX-License-Identifier: Apache-2.0
  3. // SPDX-License-Identifier: MIT
  4. /**
  5. * Send toast notifications (brief auto-expiring OS window element) to your user.
  6. * Can also be used with the Notification Web API.
  7. *
  8. * This package is also accessible with `window.__TAURI__.notification` when `tauri.conf.json > build > withGlobalTauri` is set to true.
  9. *
  10. * The APIs must be allowlisted on `tauri.conf.json`:
  11. * ```json
  12. * {
  13. * "tauri": {
  14. * "allowlist": {
  15. * "notification": {
  16. * "all": true // enable all notification APIs
  17. * }
  18. * }
  19. * }
  20. * }
  21. * ```
  22. * It is recommended to allowlist only the APIs you use for optimal bundle size and security.
  23. * @module
  24. */
  25. import { invokeTauriCommand } from './helpers/tauri'
  26. /**
  27. * Options to send a notification.
  28. */
  29. interface Options {
  30. /** Notification title. */
  31. title: string
  32. /** Optional notification body. */
  33. body?: string
  34. /** Optional notification icon. */
  35. icon?: string
  36. }
  37. /** Possible permission values. */
  38. type Permission = 'granted' | 'denied' | 'default'
  39. /**
  40. * Checks if the permission to send notifications is granted.
  41. *
  42. * @returns
  43. */
  44. async function isPermissionGranted(): Promise<boolean> {
  45. if (window.Notification.permission !== 'default') {
  46. return Promise.resolve(window.Notification.permission === 'granted')
  47. }
  48. return invokeTauriCommand({
  49. __tauriModule: 'Notification',
  50. message: {
  51. cmd: 'isNotificationPermissionGranted'
  52. }
  53. })
  54. }
  55. /**
  56. * Requests the permission to send notifications.
  57. *
  58. * @returns A promise resolving to whether the user granted the permission or not.
  59. */
  60. async function requestPermission(): Promise<Permission> {
  61. return window.Notification.requestPermission()
  62. }
  63. /**
  64. * Sends a notification to the user.
  65. *
  66. * @param options Notification options.
  67. */
  68. function sendNotification(options: Options | string): void {
  69. if (typeof options === 'string') {
  70. // eslint-disable-next-line no-new
  71. new window.Notification(options)
  72. } else {
  73. // eslint-disable-next-line no-new
  74. new window.Notification(options.title, options)
  75. }
  76. }
  77. export type { Options, Permission }
  78. export { sendNotification, requestPermission, isPermissionGranted }