ThinkChat🤖让你学习和工作更高效,注册即送10W Token,即刻开启你的AI之旅 广告
[TOC] ## 概述 进行系统通知 语法 ``` interface Notification extends EventTarget { readonly actions: ReadonlyArray<NotificationAction>; readonly badge: string; readonly body: string; // 正文 readonly data: any; readonly dir: NotificationDirection; readonly icon: string; // 通知的图标 readonly image: string; readonly lang: string; onclick: ((this: Notification, ev: Event) => any) | null; onclose: ((this: Notification, ev: Event) => any) | null; onerror: ((this: Notification, ev: Event) => any) | null; onshow: ((this: Notification, ev: Event) => any) | null; readonly renotify: boolean; readonly requireInteraction: boolean; readonly silent: boolean; readonly tag: string; readonly timestamp: number; readonly title: string; // 通知的标题 readonly vibrate: ReadonlyArray<number>; close(): void; addEventListener<K extends keyof NotificationEventMap>(type: K, listener: (this: Notification, ev: NotificationEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; removeEventListener<K extends keyof NotificationEventMap>(type: K, listener: (this: Notification, ev: NotificationEventMap[K]) => any, options?: boolean | EventListenerOptions): void; removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; } declare var Notification: { prototype: Notification; new(title: string, options?: NotificationOptions): Notification; readonly maxActions: number; readonly permission: NotificationPermission; requestPermission(deprecatedCallback?: NotificationPermissionCallback): Promise<NotificationPermission>; }; ``` ## 示例 ## hello w-rold ``` function notifyMe() { // Let's check if the browser supports notifications if (!("Notification" in window)) { alert("This browser does not support desktop notification"); } // Let's check whether notification permissions have already been granted else if (Notification.permission === "granted") { // If it's okay let's create a notification var notification = new Notification("Hi there!"); } // Otherwise, we need to ask the user for permission else if (Notification.permission !== "denied") { Notification.requestPermission().then(function (permission) { // If the user accepts, let's create a notification if (permission === "granted") { var notification = new Notification("Hi there!"); } }); } // At last, if the user has denied notifications, and you // want to be respectful there is no need to bother them anymore. } notifyMe() ``` ## 带有icon ``` var title = "Something Has Happened"; var message = "Here's something you might want to check out."; var icon = "1.png"; var notification = new Notification(title, { body: message, tag: 'simple-push-demo-notification', icon: icon, }); ``` ![](https://img.kancloud.cn/14/e8/14e8f533df2e0a176fbcf22b8d15a525_364x144.png)