美文网首页Web前端之路前端
H5 Notifications在不同浏览器中的行为

H5 Notifications在不同浏览器中的行为

作者: 张中华 | 来源:发表于2020-08-31 23:00 被阅读0次

Notifications API的使用可参看:
https://notifications.spec.whatwg.org/#example-08e8ecea
https://developer.mozilla.org/en-US/docs/Web/API/notification
尽量参看英文,中文有翻译不完整甚至有不准确的地方。

最近发现Notifications在自己的谷歌浏览器(85.0.4183.83)上使用发生了与之前不太相同的地方,就是无法触发onclick事件了!!!

代码如下:

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>

<body>
    <button id="button">测试Notification</button>
    <div id="text"></div>
    <script>
        var button = document.getElementById('button');
        var text = document.getElementById("text");

        button.onclick = function () {
            if (Notification.permission == "granted") {
                popNotice();
            } else if (Notification.permission != "denied") {
                Notification.requestPermission(function (permission) {
                    popNotice();
                });
            }
        };

        var popNotice = function () {
            if (Notification.permission == "granted") {

                var n = new Notification("系统通知:", {
                    //tag: "testTag",
                    icon: "https://ss0.bdstatic.com/5aV1bjqh_Q23odCf/static/superman/img/logo_top_86d58ae1.png",
                    body: 'hello world'
                });

                n.onshow = function (event) {
                    console.log(`on show, time: ${new Date().toISOString()}`);
                };

                n.onclick = function (event) {
                    console.log(`on click, time: ${new Date().toISOString()}`);
                };

                n.onclose = function (event) {
                    console.log(`on close, time: ${new Date().toISOString()}`);
                };
            }
        };
    </script>

</body>

</html>

于是猜想是不是自己的代码有问题,就对比下手头现有的浏览器行为,发现不同的浏览器对Notifications的支持都有不同。

谷歌浏览器(85.0.4183.83)

谷歌浏览器已经无法触发onclick事件,只能触发onshow事件,并且触发onclose的事件距点击时间较长(消息提示出现后便点击),如图所示:


谷歌浏览器

Edge(Microsoft Edge 44.18362.449.0)

Edge浏览器可以触发onshow,onclick,onclose事件,点击消息内容,会触发onclick事件,消息会自动关闭。点击右上角的符号,会触发onclose事件消息会自动关闭。如图所示:


Edge浏览器

Firefox(78.0.2 (64 位))

火狐浏览器可以触发onshow,onclick,onclose事件,点击消息内容,会触发onclick,onclose事件,消息会自动关闭。点击右上角的符号,会触发onclose事件消息会自动关闭。如图所示:


火狐浏览器

双核浏览器

火狐浏览器可以触发onshow,onclick,onclose事件,但是点击消息内容,消息不会自动关闭,需要手动添加关闭方法,不然点击消息,消息框永远不会关闭,代码如下:

                n.onclick = function (event) {
                    console.log(`on click, time: ${new Date().toISOString()}`);
                    n.close();
                };

添加完关闭方法后,与火狐浏览器行为相同。


双核浏览器

那么问题来了,谷歌浏览器不支持Notifications 的onclick回调了?onclose回调时间也不正常。是我下载的浏览器有问题还是谷歌真的做了这样子的改动?我也不知道了,希望有大佬可以指点一二...

相关文章

网友评论

    本文标题:H5 Notifications在不同浏览器中的行为

    本文链接:https://www.haomeiwen.com/subject/maapsktx.html