通知点击 - 在新标签页中打开链接并聚焦

5
function spawnNotification(theBody, theIcon, theTitle, theLink) {
  var options = {
    body: theBody,
    icon: theIcon
  }
  var notification = new Notification(theTitle, options);
  notification.onclick = function() { 
    var myWindow = window.open(theLink,"_blank");
    myWindow.focus();
  };
  setTimeout(notification.close.bind(notification), 4000);
}

当通知框被点击时,我想要打开一个新的选项卡并将其聚焦。

我正在使用上述函数来在新选项卡中打开链接并将焦点放在新打开的选项卡上。但是它没有起作用。

新选项卡已经打开,但焦点仍停留在旧选项卡上。我该如何解决这个问题?


window.open(url, '_blank')会在新标签页中打开链接,并默认将焦点放在新标签页上,因此应该有其他原因导致焦点仍然停留在原始标签页中。 - Mathias W
@MathiasW 我会编辑这个问题并添加更多的代码,以便您可以帮助我解决它。 - Anoop Mayampilly Muraleedharan
1个回答

6
function spawnNotification(theBody, theIcon, theTitle, theLink) {
  var options = {
    body: theBody,
    icon: theIcon
  }
  var notification = new Notification(theTitle, options);
  notification.onclick = function(event) {
    event.preventDefault(); // prevent the browser from focusing the Notification's tab
    window.open(theLink, '_blank');
  }

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

我已经按照上述示例更改了代码,现在它完美运行。 请参见:https://developer.mozilla.org/en-US/docs/Web/API/Notification/onclick#Examples

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接