9

如何创建设置超时的 TypeScript Web 通知?

我创建了以下代码,但无法在默认超时之前关闭通知:

export function createNotification(title: string, body: string) {
    let now: Date = new Date(Date.now());
    let date = now.add(5).seconds();

    let options = {
        body: body,
        requireInteraction: false,
        timestamp: date
    };
    new Notification(title, options);
}

作为测试,我想在 TypeScript 中创建一个持续五秒钟的通知,覆盖浏览器的默认行为。我看不到 TypeScript 类型文件中列出的任何其他对我有帮助的选项:

ES2017 通知选项

尽管我使用 Firefox 作为我的主要浏览器,但我正在使用 Chrome 开发和测试这个软件。因此,任何在 Chrome 中正常工作但不包含黑客或浏览器特定代码的解决方案都可以。

4

1 回答 1

9

你试过 Notification.close() 吗?

function spawnNotification(theBody,theIcon,theTitle) {
  var options = {
      body: theBody,
      icon: theIcon
  }

  var n = new Notification(theTitle,options);
  setTimeout(n.close.bind(n), 4000);
}

来源:https ://developer.mozilla.org/en-US/docs/Web/API/Notification/close

于 2017-12-20T14:08:39.700 回答