×

使用Notification做浏览器通知,右下角弹框,支持浏览器最小化弹出

我的笔记 我的笔记 发表于2019-09-11 09:10:41 浏览3056 评论0

抢沙发发表评论

    因为smart-web-im一直处于开发阶段,后期我打算用浏览器弹框的方式来提示用户。。先记一下笔记

效果图:

    image.png

代码如下:

<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<h2>测试消息通知</h2>

<script>
    window.onload = function () {
        suportNotify()
    }

    //判断浏览器是否支持Web Notifications API
    function suportNotify(){
        if (window.Notification) {
            // 支持
            console.log("支持"+"Web Notifications API");
            //如果支持Web Notifications API,再判断浏览器是否支持弹出实例
            showMess()
        } else {
            // 不支持
            alert("不支持 Web Notifications API");
        }
    }

    //判断浏览器是否支持弹出实例
    function showMess(){
        setTimeout(function () {
            console.log('1:'+Notification.permission);
            //如果支持window.Notification 并且 许可不是拒绝状态
            if(window.Notification && Notification.permission !== "denied") {
                //Notification.requestPermission这是一个静态方法,作用就是让浏览器出现是否允许通知的提示
                Notification.requestPermission(function(status) {
                    console.log('2: '+status);
                    //如果状态是同意
                    if (status === "granted") {
                        var m = new Notification('收到信息', {
                            body: '这里是通知内容!你想看什么客官?',  //消息体内容
                            icon:"images/img1.jpg"  //消息图片
                        });
                        m.onclick = function () {//点击当前消息提示框后,跳转到当前页面
                            window.focus();
                        }
                    } else{
                        alert('当前浏览器不支持弹出消息')
                    }
                });
            }
        },1000)
    }
</script>
</body>
</html>


我的笔记博客版权我的笔记博客版权