notifications 通知
允许用户创建、显示和更新通知
权限设置
"permissions": [
"notifications"
],
新版本Chrome浏览器禁用了MacOS本机通知
解决方案:
- 在Chrome浏览器中访问地址:chrome://flags。
- 搜索栏中搜索:notifications,找到 Enable system notifications 选项,将其选项值改为 Disabled
- 重启浏览器,问题解决。
方法
创建通知
type NotificationOptions = {
// 通知类型
type: 'basic' | 'image' | 'list' | 'progress';
// 通知图标(可以是发件人头像,应用图标等)
iconUrl: string;
// 通知标题
title: string;
// 通知内容
message: string;
// 通知按钮,最多两个
buttons: {
title: string;
}[];
// 通知优先级(从 -2 到 2。-2 是最低优先级。2 是最高的。默认值为零)
priority: number;
// 使用较低粗细字体的备用通知内容
contextMessage: string;
// 通知列表(Mac OS X 上的用户只能看到第一项)
items: {
title: string;
message: string;
}[];
// 显示通知时不应发出声音或振动。默认值为 false。
silent: boolean;
// 通知是否可关闭
requireInteraction: boolean;
// 通知进度(从 0 到 100)
progress: number;
// 通知进度状态
progressState: 'indeterminate' | 'error' | 'paused' | 'normal';
// 事件时间戳(以ms为单位)
eventTime: number;
}
chrome.notifications.create(
notificationId: string,
options: NotificationOptions,
callback?: function,
)
clear() 清除通知
清除通知
chrome.notifications.clear(
notificationId: string,
callback?: function,
)
update() 更新通知
更新通知
chrome.notifications.update(
notificationId: string,
options: NotificationOptions,
callback?: function,
)
getPermissionLevel() 获取通知权限
获取通知权限
chrome.notifications.getPermissionLevel(
callback?: function,
)
getAll() 获取所有通知
获取所有通知
chrome.notifications.getAll(
callback?: function,
)
事件
onClosed 关闭事件
当通知关闭时触发
// background.js
chrome.notifications.onClosed.addListener((notificationId, byUser) => {
console.log('🍄 background: >>>>>>>>>>>>>>>>>> 监听关闭事件', Date.now(), notificationId, byUser);
});
onClicked 点击事件
当通知被点击时触发
// background.js
chrome.notifications.onClicked.addListener((notificationId) => {
console.log('🍄 background: >>>>>>>>>>>>>>>>>> 监听点击事件', Date.now(), notificationId);
});
onButtonClicked 按钮点击事件
当通知按钮被点击时触发
// background.js
chrome.notifications.onButtonClicked.addListener((notificationId, buttonIndex) => {
console.log('🍄 background: >>>>>>>>>>>>>>>>>> 监听按钮点击事件', Date.now(), notificationId, buttonIndex);
});
onPermissionLevelChanged 权限级别变更事件
当通知权限级别变更时触发
// background.js
chrome.notifications.onPermissionLevelChanged.addListener((level) => {
console.log('🍄 background: >>>>>>>>>>>>>>>>>> 监听权限变更事件', Date.now(), level);
});
onShowSettings 显示事件
当通知显示时触发
// background.js
chrome.notifications.onShowSettings.addListener((notificationId) => {
console.log('🍄 background: >>>>>>>>>>>>>>>>>> 监听显示事件', Date.now(), notificationId);
});