How to get focus to a Chrome tab which created desktop notification?

后端 未结 5 1743
北荒
北荒 2020-12-07 14:50

I would like to implement same functionality as Gmail has nowadays. When new email arrives or new chat comes, notification popup appears and if you click it, the tab with Gm

5条回答
  •  时光说笑
    2020-12-07 15:18

    window.focus() does not always work in recent Webkit browser versions (Chrome, Safari etc). But parent.focus() does.

    Here's a complete jsfiddle: https://jsfiddle.net/wv0w7uj7/3/

    Code:

    function notifyMe() {
      if (Notification.permission !== "granted")
        Notification.requestPermission();
      else {
        var notification = new Notification('Notification title', {
          icon: 'http://cdn.sstatic.net/stackexchange/img/logos/so/so-icon.png',
          body: "You've been notified!",
        });
    
        notification.onclick = function () {
          parent.focus();
          window.focus(); //just in case, older browsers
          this.close();
        };
      }
    }
    

提交回复
热议问题