4

I want to use HTML5 notifications which work great.

The problem is that they never disappear.

How can I set a delay after which the HTML5 notification disappear?

Michael
  • 32,527
  • 49
  • 210
  • 370

2 Answers2

6

You can just call the .close() method:

var n = new Notification("Hello");
setTimeout(n.close.bind(n), 2000);

See here on MDN for details.

jfriend00
  • 683,504
  • 96
  • 985
  • 979
  • @confile - So that `n.close()` is called with the appropriate `this` value. – jfriend00 Jan 15 '16 at 15:11
  • I don't get it. Why not just do ``n.close()``? – Michael Jan 15 '16 at 15:16
  • @confile - You have to pass a reference to the method. If you just pass `n.close`, it will not call it properly. The value of `n` will be lost when the close method is called. If you pass `n.close()`, then it will be executed IMMEDIATELY, not later when the `setTimeout()` fires. The parens `()` mean to execute the function NOW. Without the parens is a function reference that `setTimeout()` can call later (which is what is wanted here). – jfriend00 Jan 15 '16 at 15:22
  • 1
    @confile - You could also use `setTimeout(function() { n.close(); }, 2000);`, but the version I show is more compact. – jfriend00 Jan 15 '16 at 15:24
1

The notification should have a built in close button, no?

HTML

<a href="#" onclick="return show()">Notify me!</a>

JS

<script>
        var Notification = window.Notification || window.mozNotification || window.webkitNotification;

        Notification.requestPermission(function (permission) {
            // console.log(permission);
        });

        function show() {
            var instance = new Notification(
                "Hey", {
                    body: "this is a message"
                }
            );

            instance.onclick = function () {
                // Something to do
            };
            instance.onerror = function () {
                // Something to do
            };
            instance.onshow = function () {
                // Something to do
            };
            instance.onclose = function () {
                // Something to do
            };

            return false;
        }
    </script>
Korgrue
  • 3,430
  • 1
  • 13
  • 20
  • 1
    I thought the point of the OP's question was that they want it displayed only for a certain amount of time and don't want the user to have to dismiss it so I'm not sure how this code solves what they were asking for. – jfriend00 Jan 14 '16 at 23:33