【前端基础问题】浏览器调起桌面通知功能 Notification

一、Notification

Notifications API 允许网页或应用程序在系统级别发送在页面外部显示的通知;这样即使应用程序空闲或在后台,Web 应用程序也会向用户发送信息。本文将介绍在您自己的应用程序中使用此 API 的基础知识。

参考链接:MDN

二、注意事项

此项功能仅在一些支持的浏览器的安全上下文(HTTPS)中可用。

三、使用步骤

1、向用户发起权限请求

权限操作有三种状态:granted、denied、default
在这里插入图片描述

if (Notification.permission === 'granted') {
	this.notify(title, options);//发起通知
} else if (Notification.permission === 'default') {
	//如果用户未被询问授权,先发起权限请求,同意后再发通知
	Notification.requestPermission(function (res) {
		if (res === 'granted') {
			this.notify(title, options);//发起通知
		}
	});
}

2、调用 Notification API 进行推送消息

function notify($title, $options) {
    var notification = new Notification($title, $options);
    notification.onshow = function (event) { console.log('show : ', event); }
    notification.onclose = function (event) { console.log('close : ', event); }
    notification.onclick = function (event) {
        notification.close();
    }
}

四、完整代码

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>浏览器消息测试</title>
</head>

<body>
    <button onclick="chromeMessageBtn()">浏览器消息测试</button>

    <script>
        //浏览器消息推送
        function chromeMessageBtn() {
            this.createNotify('测试通知', { body: '您收到一条新信息!', sticky: 'true' })
        }
        function createNotify(title, options) {
            if (Notification.permission === 'granted') {
                this.notify(title, options);//发起通知
            } else if (Notification.permission === 'default') {
                //如果用户未被询问授权,先发起权限请求,同意后再发通知
                Notification.requestPermission(function (res) {
                    if (res === 'granted') {
                        this.notify(title, options);//发起通知
                    }
                });
            }
        }
        function notify($title, $options) {
            var notification = new Notification($title, $options);
            notification.onshow = function (event) { console.log('show : ', event); }
            notification.onclose = function (event) { console.log('close : ', event); }
            notification.onclick = function (event) {
                notification.close();
            }
        }

    </script>
</body>

</html>

五、效果

在这里插入图片描述

在这里插入图片描述
在这里插入图片描述

  • 1
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

@Dai

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值