9

How do I create a TypeScript web notification with a set timeout?

I created the following code but doesn't work in closing the notification before the default timeout:

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);
}

As a test I want to create a notification in TypeScript which lasts five seconds, overriding the browsers default behaviour. I can't see any further options listed in the TypeScript typings file which would be helpful to me:

ES2017 Notification Options

I'm using for developing and testing this software using Chrome, although I use Firefox as my main browser. So any solutions which works correctly in Chrome, but doesn't include hacks or browser specific code would be fine.

wonea
  • 4,783
  • 17
  • 86
  • 139
  • 2
    " but doesn't work in closing the notification before the default timeout:" can you be clearer about what are you expecting as behavior for your class ? – Pac0 Dec 20 '17 at 13:40
  • `now.add()` ... doesnt exist on the Date class. Have you considered using something like momentjs for your date manipulations. The moment equivalent would be `moment().add(5, 'seconds')`. – DarkNeuron Dec 20 '17 at 13:46
  • Also, web notifications are buggy in Firefox: https://caniuse.com/#feat=notifications ("Firefox notifications disappear after a few seconds") – DarkNeuron Dec 20 '17 at 13:48
  • @DarkNeuron I'm using DateJS typings – wonea Dec 20 '17 at 13:52

1 Answers1

9

Did you try 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);
}

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

Gabriel Bleu
  • 9,703
  • 2
  • 30
  • 43