在Chrome通知中使用for循环会导致错误的onclick链接

时间:2016-08-22 04:48:34

标签: javascript google-chrome notifications

我一直在编写一个调用for循环的Javascript文件,并且在循环的每次迭代中以编程方式创建一个新的链接,通过浏览器推送通知将其推送给用户。这些唯一链接也作为onclick事件附加到通知中。我运行代码并尝试单击通知,但是我发现,而不是每个通知都有自己唯一的onclick链接,所有连续通知都会在最近的通知上进行。

我在这里添加了一个准系统代码,用于演示我面临的问题:https://jsbin.com/loyeviguqu/1/edit?html,js,output

*编辑:对不起我很快意识到我已经链接到了错误的jsbin,现在更新了正确的链接

根据我编写的代码,您会看到我创建了3个链接google.com/0,google.com / 1,google.com / 2,带有for循环。此外,在每次迭代的for循环中,我将链接作为onclick事件附加到通知中。但是,您会看到点击3个通知中的任何一个将始终生成google.com/2,而不是其他任何两个。然而,通知中的文字保留了它们的独特性。

我目前的怀疑是每次我在通知上附加一个onclick它会覆盖旧的通知,但是我对如何解决这个问题感到茫然。

对此问题的任何解释或见解将不胜感激!谢谢!

1 个答案:

答案 0 :(得分:0)

// request permission on page load
document.addEventListener('DOMContentLoaded', function () {
  if (Notification.permission !== "granted")
    Notification.requestPermission();
});

function notifyMe() {
  if (!Notification) {
    alert('Desktop notifications not available in your browser. Try Chromium.'); 
    return;
  }

  if (Notification.permission !== "granted")
    Notification.requestPermission();
  else {

        var string = "http://google.com/" + 1;
    var notification = new Notification(string, {
      icon: 'http://cdn.sstatic.net/stackexchange/img/logos/so/so-icon.png',
      body: "I should be linking to " + string ,
    });

    notification.onclick = function () {
      window.open(this.title);      
    };

     var string = "http://google.com/" + 2;
    var notification = new Notification(string, {
      icon: 'http://cdn.sstatic.net/stackexchange/img/logos/so/so-icon.png',
      body: "I should be linking to " + string ,
    });

    notification.onclick = function () {
      window.open(this.title);      
    };

     var string = "http://google.com/" + 3;
    var notification = new Notification(string, {
      icon: 'http://cdn.sstatic.net/stackexchange/img/logos/so/so-icon.png',
      body: "I should be linking to " + string ,
    });

    notification.onclick = function () {
      window.open(this.title);      
    };
  }

}