Html5的Notification实现实例

官网API说明:
https://developer.mozilla.org/en-US/docs/Web/API/notification


/*1、弹窗样式由浏览器决定,无法自定义
唯一破局方式:html生成图片,以图片方式插入

2、结合WebSocket实现后台对前台的消息推送

3、代码实例*/

/**
 * 消息弹出
 * @param data:用户数据
 * @returns {*}
 */
function notifyMe(data) {
    if (!data || !reqPermit4Notify()) {
        return;
    }

    var data = JSON.parse(data);
    var iconUrl = "/project/images/pic1.png";

    var title = "Title";//标题
    var options = {
        body: "Content",//内容
        lang: 'zh-CN',
        dir: "ltr",//方向,从左向右
        tag: data.tag,//多个标签页同时打开,会弹出多个相同内容弹窗,仅当各弹窗tag相同时,仅弹出一个
        renotify: false,//复用弹窗
        icon: iconUrl,
        // image: imageUrl,
        data: {
            url: "www.baidu.com"
        },
        requireInteraction: true,//持续显示
        // timestamp:"",指定时间推送
        // vibrate: [200, 100, 200],震动模式
    };

    var notify = new Notification(title, options);
    notify.onerror = function (event) {
        console.log("Notification Error");
    };
    notify.onshow = function (event) {
        console.log("Notification Show");
    };
    notify.ondisplay = function (event) {
        console.log("Notification Display");
    };
    notify.onclick = function (event) {
        console.log("Notification Click");
        window.open(this.data.url, '_blank');
        this.close();
    };
    notify.onclose = function (event) {
        console.log("Notification Close");
    };

    return notify;
}

/**
 * 请求浏览器弹出授权
 */
function reqPermit4Notify() {
    if (!("Notification" in window)) {//浏览器支持
        console.log("Browser not supported Html5 Notification");
        return false;
    }

    if (Notification.permission == "denied") {//用户禁用
        console.log("User refused to show Html5 Notification");
        return false;
    }

    if (Notification.permission != "granted") {//用户未授权
        Notification.requestPermission(function (permission) {
            if (permission != 'granted') {
                console.log("User forbit the Html5 Notification");
                return false;
            }
            return true;
        });
    }

    return true;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值