html5 api通知,HTML5基础知识 - JavaScript API - Notifications - 简单通知

这篇博客探讨了如何使用JavaScript处理浏览器的通知功能。它详细介绍了如何检查用户权限,请求权限,以及在用户同意接收通知后发送多个通知。代码示例展示了在用户点击按钮时触发通知,并使用Notification API进行实现。同时,对于用户未明确许可的情况,提供了备选的弹窗提示方案。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

JavaScript

语言:

JaveScriptBabelCoffeeScript

确定

window.addEventListener('load', function() {

// At first, let's check if we have permission for notification

// If not, let's ask for it

if (window.Notification && Notification.permission !== "granted") {

Notification.requestPermission(function(status) {

if (Notification.permission !== status) {

Notification.permission = status;

}

});

}

var button = document.getElementsByTagName('button')[0];

button.addEventListener('click', function() {

var n = 1; //change this number and Notification tag parameter to see many notifications.

// If the user agreed to get notified

// Let's try to send ten notifications

if (window.Notification && Notification.permission === "granted") {

for (var i = 0; i < n; i++) {

// Thanks to the tag, we should only see the last notification

var n = new Notification("Hi Dude #" + i + ", any question on Techbrood?", {

body: 'Best viewed in Chrome, Do not use IE!',

icon: '/assets/check.png',

tag: 'soManyNotification',

});

}

}

// If the user hasn't told if he wants to be notified or not

// Note: because of Chrome, we are not sure the permission property

// is set, therefore it's unsafe to check for the "default" value.

else if (window.Notification && Notification.permission !== "denied") {

Notification.requestPermission(function(status) {

if (Notification.permission !== status) {

Notification.permission = status;

}

// If the user said okay

if (status === "granted") {

for (var i = 0; i < n; i++) {

// Thanks to the tag, we should only see the last notification

var n = new Notification("Hi Dude #" + i + ", any question on Techbrood?", {

body: 'Best viewed in Chrome, Do not use IE!',

icon: '/assets/check.png',

tag: 'soManyNotification',

});

}

}

// Otherwise, we can fallback to a regular modal alert

else {

alert("Hi!");

}

});

}

// If the user refuses to get notified

else {

// We can fallback to a regular modal alert

alert("Hi!");

}

});

});

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值