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

后端 未结 5 1753
北荒
北荒 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:09

    It should be this.close() rather than this.cancel(), like this:

    var n = window.webkitNotifications.createNotification('ico.gif','Title', 'Text');
    n.onclick = function(x) { window.focus(); this.cancel(); };
    n.show();
    
    0 讨论(0)
  • 2020-12-07 15:13

    It's not really good practice to use the onclick property, use the addEventListener for vanilla javascript or on method for jQuery.

    var notify = new Notification('Test notification');
    

    Vanilla:

    notify.addEventListener('click', function(e) {
        window.focus();
        e.target.close();
    }, false);
    

    jQuery:

    $(notify).on('click', function(e) {
        window.focus();
        e.target.close();
    });
    
    0 讨论(0)
  • 2020-12-07 15:18

    Using Notifications.

    if (typeof Notification !== 'undefined') {
      alert('Please us a modern version of Chrome, Firefox, Opera or Safari.');
      return;
    }
    
    Notification.requestPermission(function (permission) {
      if (permission !== 'granted') return;
    
      var notification = new Notification('Here is the title', {
        icon: 'http://path.to/my/icon.png',
        body: 'Some body text',
      });
    
      notification.onclick = function () {
        window.focus();
      };
    });
    
    0 讨论(0)
  • 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();
        };
      }
    }
    
    0 讨论(0)
  • 2020-12-07 15:21

    You can just place window.focus() in Google Chrome. It will focus to that window when clicked.

    var n = window.webkitNotifications.createNotification('ico.gif', 'Title', 'Text');
    n.onclick = function(x) { window.focus(); this.close(); };
    n.show();
    

    I opened the inspector in Gmail, added the above code, moved to a different tab, and ran it. The notification appeared and once clicked, it brought me back to Gmail.

    0 讨论(0)
提交回复
热议问题