js系统通知

这段代码展示了如何在浏览器中实现通知功能。首先检查`window.Notification`是否存在,然后请求用户的许可。如果用户允许,创建一个包含指定标题、正文和图标的Notification,并设置关闭、点击、显示和关闭事件的回调函数。点击通知会打开指定链接,同时记录日志。如果用户拒绝或未做决定,会有相应的日志输出。

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

if(undefined !== window.Notification) {
    if (Notification.permission === "default") {
        Notification.requestPermission();
    }
}
Notification.requestPermission(function() {
    if(Notification.permission === 'granted') {
        // 用户点击了允许
        let n = new Notification('华为好', {
            body: '华为给我涨智慧',
            icon: 'https://res.hc-cdn.com/cnpm-header-and-footer/2.0.6/base/header-china/components/images/logo.svg'
        })

        setTimeout(() => {
            n.close();
        }, 8000)
        
        n.onclick = function(e) {
            window.open("https://www.xxxx.com")
            console.log(1, e);
        }

        n.onerror = function(e) {
            console.log(2, e);
        }

        n.onshow = function(e) {
            console.log(3, e);
        }

        n.onclose = function(e) {
            console.log(4, e);
        }
        
    }else if(Notification.permission === 'denied') {
		console.log("用户点击了拒绝");
    }else {
    	console.log("用户没有做决定");
    }
})

核心代码如下 :

        // 用户点击了允许
        let n = new Notification('华为好', {
            body: '华为给我涨智慧',
            icon: 'https://res.hc-cdn.com/cnpm-header-and-footer/2.0.6/base/header-china/components/images/logo.svg'
        })
        setTimeout(() => {
            n.close();
        }, 8000)
        n.onclick = function(e) {
            window.open("https://www.baidu.com")
            console.log(1, e);
        }
        n.onshow = function(e) {
            console.log(3, e);
        }
        n.onclose = function(e) {
            console.log(4, e);
        }
        
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值