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

标签 javascript api notifications

我通过将以下脚本添加到页面底部,在标准 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);
  });

}

关于javascript - 使用通知 API 时如何向通知添加 URL?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61169326/

相关文章:

javascript - 如何使用 Jasmine 在 AngularJS 中测试 .catch Promise 返回?

javascript - AWS Javascript SDK CORS错误

javascript - select2 使用多个 false 时显示 undefined

java - 怎么可以没有。 OpenOffice.org 电子表格中的页面数可以通过编程方式获取吗?

php - 带进度条的 Paypal 捐赠跟踪

ios - 无声通知

java - 通知 oreo api 26 - 工作正常,现在不行

ipad - 意外的 UIDeviceOrientationDidChangeNotification 被调用

javascript - 给定纬度和经度,在 D3 地理投影上绘制点

linux - Quotactl block 大小