推荐答案
// www.javascriptcn.com code example
function requestNotificationPermission() {
if (!("Notification" in window)) {
console.error("This browser does not support notifications.");
return Promise.reject("Notifications not supported");
}
if (Notification.permission === "granted") {
return Promise.resolve("Permission already granted");
}
return Notification.requestPermission().then(permission => {
if (permission === "granted") {
return Promise.resolve("Permission granted");
} else {
return Promise.reject("Permission not granted");
}
});
}
function showNotification(title, options) {
return requestNotificationPermission()
.then(() => {
const notification = new Notification(title, options);
return Promise.resolve(notification);
})
.catch((error) => {
console.error("Failed to show notification:", error);
return Promise.reject(error);
});
}
// Example Usage:
// 1. 检查是否已经有权限,如果没请求就请求
requestNotificationPermission()
.then((message) => {
console.log(message)
// 如果已经有权限,或者请求成功则显示通知
return showNotification("Hello!", {
body: "This is a desktop notification!",
icon: "/notification-icon.png" // Optional: Path to a notification icon
})
})
.then(notification => {
console.log("notification success:", notification)
})
.catch(error => {
console.error("notification failed:", error);
});
// 2. 直接显示通知
// showNotification("Important Message", {
// body: "This is an urgent notification.",
// icon: "/urgent-icon.png",
// vibrate: [200, 100, 200] // Optional: Vibration pattern for supporting devices
// })
// .then(notification => {
// console.log("notification success:", notification)
// })
// .catch(error => {
// console.error("notification failed:", error);
// });本题详细解读
Notification API 简介
JavaScript 的 Notification API 允许网页向用户发送桌面通知,即使浏览器窗口处于最小化或后台状态。这是一个强大的功能,能够提升用户体验,例如及时提醒用户新的消息、更新或其他事件。
核心步骤
检测支持性: 首先,需要检查浏览器是否支持 Notification API,通过
if ("Notification" in window)判断。请求权限: 在发送任何通知之前,必须先请求用户的许可。使用
Notification.requestPermission()方法来发起权限请求。该方法返回一个 Promise,它会 resolve 为 "granted"、"denied" 或 "default" (表示用户尚未做出选择)。创建通知: 如果权限被授予,就可以使用
new Notification(title, options)构造函数来创建通知。title参数是通知的标题,options是一个对象,可以包含:body: 通知的内容。icon: 通知的图标,通常是一个图片 URL。vibrate: 震动模式(数组表示)。tag: 为通知添加标签,相同的标签的新通知会替换旧的通知,而不是显示多个。- 更多配置项请查阅 MDN 文档。
处理权限状态:
Notification.permission: 可以直接获取当前的权限状态。
代码解释
requestNotificationPermission() 函数
该函数首先检查浏览器是否支持 Notification API,如果不支持则返回一个 rejected Promise。接着,它检查是否已经获得了权限,如果已经获得则返回一个 resolved Promise,否则,调用 Notification.requestPermission() 来请求权限,并根据用户的选择返回 resolved 或 rejected 的 Promise。
showNotification() 函数
该函数首先调用 requestNotificationPermission() 来确保已经获得了权限,然后创建一个新的通知,并返回一个 Promise,如果创建失败会catch错误并返回一个 rejected Promise。
使用示例
示例代码演示了如何使用 requestNotificationPermission 来获取权限,然后使用 showNotification 创建并显示通知。还演示了如果请求权限失败或者通知显示失败的情况。
注意事项
- HTTPS: Notification API 只能在 HTTPS 协议下使用(或者本地开发环境)。
- 用户体验: 请合理使用通知,不要过度打扰用户。
- 权限状态: 用户可以随时在浏览器设置中更改通知权限。
- 不同的通知状态: 要根据不同的权限状态(granted, denied, default)来做出相应的处理,避免出现意外行为。
- 兼容性: 虽然 Notification API 的兼容性已经相当不错,但是仍需考虑旧浏览器的兼容处理方案。