Joke Collection Website - Blessing messages - 如何使用HTML5的通知API
如何使用HTML5的通知API
1、申请权限
出于安全考虑,要发送桌面消息,需要先申请用户授权通知。对象提供了一个静态的方法——request permit(),它接收一个回调函数作为参数,并把返回值传递给回调函数作为参数:
notification . request permission(函数(状态){
if(Notification.permission!= = status){
notification . permission = status;);
返回值为字符串,有以下三个值:
默认
授予
拒绝
默认为默认,也就是需要询问,表现和拒绝一样p < . 5 > 2、创建消息
用户授权以后,就可以通过下面方式创建一条桌面提醒了:
var n =新通知(标题,选项);
选项为字典,传入通知对象的属性第三点。包含属性
通知对象有如下几个只读属性:
目录(文字方向,经测试都不支持)
郎(语言)
正文(消息体)
标签(标签)
图标(图标地址)
这
几个属性都可以在创建消息的时候,作为选择权传入通知构造函数。提一下标签属性,在有很多消息的时候,这个属性就非常有用,
它会用拥有相同标签的最新的消息取代之前的消息,只显示一条最新的消息。比如在一个聊天室系统中,同时和几个人在聊天的时候,就可以以人名为标签显示
不同人的最新消息第四章。定义事件
通知对象有四个事件,分别是onshow()
onclick()
onclose()
on error()
分别在消息显示、被点击、被关闭和出错的时候被触发。下面的例子中完整的展示了这四个事件的使用。通常情况下,只需要处理点击事件就够了,比如点击消息后跳转到某一特定的页面p
举例说明:
window . addevent listener(" load ",function(){
if(Notification & amp;& amp通知.许可!= = " granted "){
notification . request permission(function(status){
if(notification . permission!= = status){
notification . permission = status;);
}
var button = document . getelementsbytagname(" button ")[];button.addEventListener("click ",function(){
var t = new Date()。toLocaleString();
var options={
dir: "ltr ",
lang: "utf-8 ",
icon:"/static/avatar/m _ default . png ",
body:"你好呀,欢迎留言交流呀"
};如果(通知& amp& ampNotification . permission = = = " granted "){
var n = new Notification(" HUSTecho:"+t,options);n . on show = function(){
console . log("你骗到我了!");
};n.onclick = function() {
alert("你点了我!");
window . location = "/";
};n . onclose = function(){
console . log("通知已关闭!");
};n . on error = function(){
console . log("出现错误");否则如果(通知& amp& amp通知.许可!== "拒绝"){
notification . request permission(function(status){
if(notification . permission!= = status){
notification . permission = status;
}
if(status = = = " granted "){
for(var I = ;我& lt3;i++){
var n =新通知(" Hi!"+ i,{
tag: "Beyoung ",
icon:"/static/avatar/b _ default . png ",
body:"你好呀,我是第"+ i +"条消息啦!"
});}
}
});else{
alert("嗨!););
});
- Related articles
- Mobile inter-provincial long distance preferential plan
- Boyfriend always has diarrhea and a stomachache. Every time he sends me a text message, I don't know what to say.
- Broadcast terms on platforms and carriages of Guangzhou metro
- What should I do if the purchased "Honor of Kings" account fails to detect face recognition?
- What is the message of Eid al-Adha?
- I can't receive SMS on my mobile phone. When someone sends me a text message, I have to turn it off and then turn it on. Why?
- Golden Tax Disk sent an email, prompting that the format document and invoice failed to be signed during delivery.
- Can Unicom check the SMS content of the main and secondary cards?
- What monthly service can China Telecom's mobile phone provide?
- The transaction status of China Bank is unknown. Please check the account balance.