如何检查用户是否在javascript中点击了关闭

时间:2018-05-15 07:29:17

标签: javascript html5 notifications

在那里,我编写了一个默认的 HTML5 桌面通知,当我关闭通知并刷新页面时,通知再次回来我希望通知在关闭时永远不会回来

继承我的代码

 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('TITLE OF NOTIFICATION', {
      icon: 'http://carnes.cc/jsnuggets_avatar.jpg',
      body: "Hey! You are on notice!",
    });

    notification.onclick = function () {
      window.open("http://carnes.cc");      
    };
    setTimeout(notification.close.bind(notification), 7000); 
  }

}
notifyMe();
希望有人可以帮助我

THANKYOU

2 个答案:

答案 0 :(得分:0)

您可以将已显示的通知跟踪到localStorage。如下例所示:

function notify() {
    const notifications = localStorage.getItem('notifications', ['TITLE OF NOTIFICATION']) || [];
    const notifiedIndex = notifications.indexOf('TITLE OF NOTIFICATION');
    if (notifiedIndex > -1) {
        var notification = new Notification('TITLE OF NOTIFICATION', {
            icon: 'http://carnes.cc/jsnuggets_avatar.jpg',
            body: "Hey! You are on notice!",
        });

        notification.onclick = function() {
            window.open("http://carnes.cc");
        };
        setTimeout(notification.close.bind(notification), 7000);
        notifications.push('TITLE OF NOTIFICATION');
        localStorage.setItem('notifications', notifications)

    }

}

答案 1 :(得分:0)

我认为你可以使用localStorage。



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() {
      if (localStorage.close) {
          return false;
      }


    var notification = new Notification('TITLE OF NOTIFICATION', {
      icon: 'http://carnes.cc/jsnuggets_avatar.jpg',
      body: "Hey! You are on notice!",
    });

    notification.onclick = function () {
      window.open("http://carnes.cc");
    };

    notification.onclose = function () {
        localStorage.close = true;
    };

    setTimeout(notification.close.bind(notification), 7000);
  }

}
notifyMe();