Mozilla上使用Notification.requestPermission()出现错误

19

我正在尝试获取Mozilla的通知,但它不断地抛出这个错误。

仅允许在短时间运行的用户生成事件处理程序内请求通知权限。

这是我的代码。同样的代码在Chrome、EDGE和Opera上正常工作。

Notification.requestPermission().then(function (status) {
    if (status === 'denied') {
        //
    } else if (status === 'granted') {
        //
    }
});

我发现了一些与此相关的问题,但是它们对我没有帮助。

3个回答

24
那个消息的意思是你的订阅代码必须在用户生成的事件中调用,比如点击事件。
可能你正在尝试在页面加载时订阅用户,但在某些浏览器上(如Firefox和Safari)这是不可能的,因为它被认为是对用户的干扰。
这就是为什么许多推送服务(如OneSignal、Pushpad等)建议使用双重确认的原因之一:首先你需要展示一个使用HTML / CSS设计的订阅提示或按钮,然后,在点击按钮后,你实际上请求权限(即你上面的代码)。

1
@JaberKibria 实际上这就是我说的... 你需要在回调函数中请求 click 或其他用户触发事件的权限。 - collimarco

9
这段代码对我有用:
JS
if (Notification.permission === 'granted') {
    //do something
}
else if (Notification.permission === 'default') {
    $('#allow-push-notification-bar').show();
}

$('#allow-push-notification').click(function () {
    $('#allow-push-notification-bar').hide();
    Notification.requestPermission().then(function (status) {
        if (status === 'denied') {
            //do something
        } else if (status === 'granted') {
            //do something
        }
    });
});

HTML

<div id="allow-push-notification-bar" class="allow-push-notification-bar">
    <div class="content">
        <div class="text">
            Want to get notification from us?
        </div>
        <div class="buttons-more">
            <button type="button" class="ok-button button-1" id="allow-push-notification">
                Yes
            </button>
            <button type="button" class="ok-button button-1" id="close-push-notification">
                No
            </button>
        </div>
    </div>
</div>

加载网页后会弹出一个带有两个按钮(/)的弹窗。点击,浏览器将询问是否允许通知。

6

我也遇到过这样的情况。如果你不想使用按钮或其他元素事件,可以使用更高级别的文档点击事件,然后从那里请求权限。

document.addEventListener('click', () => {
        Notification.requestPermission().then(function (status) {
        if (status === 'denied') {
            //
        } else if (status === 'granted') {
            //
        }
    });
})

1
最好在第一次点击后删除该事件处理程序。 - bozdoz

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接