如何在使用通知 API 时向通知添加 URL?

How do I add a URL to a notification when using the notification API?

我通过将以下脚本添加到页面底部,在标准 index.html 文件中创建了一个简单的通知。但是,我的目标是在通知中添加 URL,这样当用户点击通知时,他们会被带到特定的 URL (window.open).我知道这可以在 Google 上搜索答案时完成,许多网站都有通知,点击后导航到不同的页面或网站。尽管如此,我还没有找到可以开始工作的解决方案。欢迎任何帮助。

    Notification.requestPermission();
Notification.requestPermission((permission) => {
  switch (permission) {
    case 'granted': {
      console.log('Now we can send notifications!');
      doNotify();
      break;
    }
    case 'denied': {
      console.log('User close the request pop-up!')
    }
  }
});

function doNotify(){
        const title = "Test notification";
        const img = "https://via.placeholder.com/600x400";
        const text = Lorem ipsum;

        const options = {
            body: text,
            icon: "https://via.placeholder.com/600x400",
            data: {
            },
            vibrate: [200, 100, 200],
            tag: "new-product",
            image: img,
            badge: "https://via.placeholder.com/128x128",
        };

        notification.onclick = function(event) {
          event.preventDefault(); // prevent the browser from focusing the Notification's tab
          window.open('http://www.mozilla.org', '_blank');
        }

      navigator.serviceWorker.ready.then(function(serviceWorker) {
        serviceWorker.showNotification(title, options);
      });

    // setTimeout( n.close.bind(n), 9000); //close notification after 3 seconds
}

你漏掉了一行,这行对它的工作非常重要。使用 Notification 构造函数定义一个通知,您可以在其中输入 titleoptions 变量。

function doNotify() {

  const title = "Test notification";
  const img = "https://via.placeholder.com/600x400";
  const text = "Lorem ipsum";

  const options = {
    body: text,
    icon: "https://via.placeholder.com/600x400",
    data: {},
    vibrate: [200, 100, 200],
    tag: "new-product",
    image: img,
    badge: "https://via.placeholder.com/128x128",
  };

  // Add this line.
  const notification = new Notification(title, options);

  notification.onclick = function(event) {
    event.preventDefault(); // prevent the browser from focusing the Notification's tab
    window.open('http://www.mozilla.org', '_blank');
  }

  navigator.serviceWorker.ready.then(function(serviceWorker) {
    serviceWorker.showNotification(title, options);
  });

}