2

Here is my scenario:

  • a client has opened a tab with my web app in it
  • whenever there is an incoming connection I would like to notify him via Notifications API
  • after clicking notification he should be redirected to this page / opened tab
  • there he should see confirmation popup where he can decide if he wants to accept connection

I know how to do each part, but I do have problems with the correct order. I believe it has something to do with JS call stack. In the following code confirmation window is always first. Only after confirming it (or not) notification displays.

let n = new Notification("Incomming call");
let c = confirm('Do you accept?')

if(c) {
  return this.peer;
}

How can I switch order? First notification, then confirmation prompt.

alecxe
  • 462,703
  • 120
  • 1,088
  • 1,195
tomatow
  • 43
  • 4

1 Answers1

1

Notifications are asynchronous. They trigger events when the user interacts with them. You can handle the close event to execute your code when the user closes the notification.

let n = new Notification("Incomming call");
n.onclose = () => {
    let c = confirm("Do you accept?");
    if (c) {
        do_something(this.peer);
    }
};

Note that you can't return anything from the onclose function, since it runs asynchronously. You need to do whatever would have been done with the return value in the callback function (promises could be useful in structuring the code more clearly). See How do I return the response from an asynchronous call?

Barmar
  • 741,623
  • 53
  • 500
  • 612