如何检查通知是否已在javascript中关闭

时间:2018-06-26 05:57:23

标签: javascript notifications

我有一个问题,通知弹出时通知没有关闭,刷新页面时我又关闭了通知再次出现,所以我想检查他们是否单击了通知上的关闭按钮

这是我的通知代码

<script>

        function notifyMe() {
          if (!("Notification" in window)) {
            alert("This browser does not support system notifications");
          }
          else if (Notification.permission === "granted") {
            notify();
          }
          else if (Notification.permission !== 'denied') {
            Notification.requestPermission(function (permission) {
              if (permission === "granted") {
                notify();
              }
            });
          }

          function notify() {
            var notification = new Notification('This months topic is stranger danger', {
              icon: 'assets/qr-codes/studentmeshCourseVideo.png',
              body: "this months topic is stranger danger click on me to a video that studentmesh has provided to educate your child about stranger danger or scan the qr code in shazam to get to the video",
            });

            notification.onclick = function () {
              window.open("assets/course-videos/strangerDanger.mp4");      
            };


          }

        }
        notifyMe();
</script>

谢谢

1 个答案:

答案 0 :(得分:0)

您应将通知状态存储在本地存储中。当用户单击关闭按钮时,您应该在本地存储中进行编写,例如:localStorage.setItem('notification-closed',true)

当通知呼叫时,请检查本地存储标志,例如localStorage.getItem('notification-closed'),如果为true,则不会再次显示通知。

 function notifyMe() {
      if(localStorage.getItem('notification-closed')) {
           return;
      }

      if (!("Notification" in window)) {
        alert("This browser does not support system notifications");
      }
      else if (Notification.permission === "granted") {
        notify();
      }
      else if (Notification.permission !== 'denied') {
        Notification.requestPermission(function (permission) {
          if (permission === "granted") {
            notify();
          }
        });
      }

      function notify() {
        var notification = new Notification('This months topic is stranger danger', {
          icon: 'assets/qr-codes/studentmeshCourseVideo.png',
          body: "this months topic is stranger danger click on me to a video that studentmesh has provided to educate your child about stranger danger or scan the qr code in shazam to get to the video",
        });

        notification.onclick = function () {
          window.open("assets/course-videos/strangerDanger.mp4");      
        };


      }

    }