天天看點

【VUE】浏覽器消息通知(聲音提醒,标題欄閃動,彈框提醒)

思路:

  • 浏覽器通知使用Notification,詳情可檢視Notification.Notification()
  • 标題欄閃動利用循環實作
  • 聲音提醒可以使用播放本地音頻實作

    總結:在目前頁面接收到消息時,聲音提醒,當不在目前頁面接收到消息時,聲音+閃動+彈框提醒

實作:

//申請浏覽器通知權限,具體參見上面文檔連結
notification(){
      let that=this;
      if (!("Notification" in window)) {
        console.log("浏覽器不支援消息通知");
        return;
      }
      Notification.requestPermission(function (permission) {});
}
           

//當需要通知時

//聲音提醒 
   that.$refs.audioTip.load();
   that.$refs.audioTip.play();
 //如果不是目前頁面,标題欄閃動+消息提示
      if(document.hidden){
        var options = {
          body: '您有新的未讀消息,請及時處理',
          silent: true
        }
        var notification = new Notification('消息通知', options);
        notification.onclick=function(){
          window.open(`頁面連結`, '_blank');
        }
          //标題欄閃動
          var defaultTitle = document.title;
          if(that.isReceive){
            return;
          }else{
            that.isReceive=true;
          }
          that.timer=setInterval(function(){
              var title = document.title;
              if (document.hidden&&that.isReceive) {
                  if (/你有新消息/.test(title) == false) {
                      document.title = '【你有新消息】';    
                  } else {
                      document.title = defaultTitle;
                  }
              } else {
                  that.isReceive=false;
                  document.title = defaultTitle;
              }
            }, 500);
      }
           

本地音頻參見【VUE】播放本地語音/音頻

watch: {
    isReceive(current, old){
      let that=this;
      if(!current){
        clearInterval(that.timer);    //停止
      }
    }
  },
           

問題:

  • document.hidden判斷是否在目前頁面,也可以使用window.onfocus ,但是我看到說window.onfocus 有時會錯誤觸發HTML5 Notification實作浏覽器通知
  • silent: true 處理Notification的預設自帶聲音
  • notification.onclick點選後可以跳轉到想去的頁面
  • document.title擷取目前的标題欄
  • 如果目前已經在setInterval,就沒有必要再次setInterval,是以定義了一個變量isReceive來控制是否重複循環

繼續閱讀