基於LC push的瀏覽器桌面提醒快速集成方案

序言

最近要做一個桌面提醒功能,類似tower的右側彈出式提醒,這裏給出一個快速集成方案吧,因爲要研究的東西蠻多的,沒有太多的時間去做。

傳統方案

  1. 與服務器保持長連接
    使用websocket與服務器保持長連接,監聽服務器的請求,服務器端創建push給網頁端,網頁端收到消息。
  2. html5 Notification
    html5的notification,無論你在看哪個頁面,只要有消息都應該能推送給我看到,並展示到桌面上,這就是webkitNotification要解決的問題。 Notification生成的消息不依附於某個頁面,僅僅依附於瀏覽器。

自己搭建websocket和研究notification都有很大的學習成本,下一節介紹快速搭建方案。

基於LC push 的方案

LC ,leancloud,一個挺有名的sass服務吧,使得開發者只需要關注業務邏輯。
Github 倉庫地址:https://github.com/leancloud/js-push-sdk

var push = AV.push({
            appId: appId,
            appKey: appKey
        });

        notify.requestPermission(0);
        // 可以鏈式調用
        push.open(function () {
            console.log('可以接收推送');
        });

        // 監聽推送消息
        push.on('message', function (data) {
            console.log('message');
            console.log(JSON.stringify(data));

            notify.createNotification("通知", {body: data.alert, icon: "/img/icon-57.jpg"});
        });

        // 監聽網絡異常
        push.on('reuse', function () {
            console.log('網絡中斷正在重試');
        });

        console.log(window.sessionStorage.userId)
        push.subscribe([window.sessionStorage.userId], function (data) {
            console.log('關注新的頻道');
        });

桌面提醒,推薦大寫的HTML5-Desktop-Notifications
https://github.com/ttsvetko/HTML5-Desktop-Notifications

demo中用了angular,寫了大段的配置,其實並沒有太多的作用,平常用呢只用一行代碼就夠了,0,1,2的具體配置可以多研究下html5 的notification的api

notify.requestPermission(0);

在後臺發推送,已解決


雖然實現了功能,但是有時間還是要對websocket和html5
的notification api進行深入研究纔好O(∩_∩)O~

ITDogFire–sky

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章