4

[Go] Go语言实战-基于websocket浏览器通知的实现

 3 years ago
source link: https://studygolang.com/articles/35015?fr=sidebar
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

[Go] Go语言实战-基于websocket浏览器通知的实现

mob604756fb8908 · 5天之前 · 371 次点击 · 预计阅读时间 1 分钟 · 大约8小时之前 开始浏览    

当我们使用了websocket技术实现了实时的推送访客来到消息,但是我们只能随时看着页面不离开才能知道有访客来到

现在增加浏览器的通知消息,就可以只要打开着界面,不用一直盯着,干别的事去就可以了,有新消息会从右下角弹出来

测试地址如下,当有访客点击咨询按钮时,客服后台会弹出提示:

https://gofly.sopans.com/index

61c947bdec74538728cde5449750e570.png

首先要明确一点,现在的通知只能在https的环境下使用 , 非https , 不能使用浏览器通知,Notification.permission返回的是禁止

             notify(title, options, callback) {                    // 先检查浏览器是否支持
                    if (!window.Notification) {                        return;
                    }                    var notification;                    // 检查用户曾经是否同意接受通知
                    if (Notification.permission === 'granted') {
                        notification = new Notification(title, options); // 显示通知
                    } else {                        var promise = Notification.requestPermission();
                    }                    if (notification && callback) {
                        notification.onclick = function(event) {
                            callback(notification, event);
                        }
                    }
             },
notify("标题", {
                        body: "内容",
                        icon: "头像"
                    }, function(notification) {

                        notification.close();

});

websocket部分就是监听onmessage方法,根据返回的json消息字段进行区分判断,这里是需要自己来定义,也可以参考上面地址的源代码


有疑问加站长微信联系(非本文作者)

280

About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK