Notification.requestPermission() 在 Mozilla 上抛出错误

Jab*_*ria 8 mozilla web-push

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

通知权限只能从短期运行的用户生成的事件处理程序内部请求。

这是我的代码。相同的代码在 Chrome、EDGE 和 Opera 上运行良好。

Notification.requestPermission().then(function (status) {
    if (status === 'denied') {
        //
    } else if (status === 'granted') {
        //
    }
});
Run Code Online (Sandbox Code Playgroud)

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

col*_*rco 15

该消息意味着您的订阅代码必须在用户生成的事件中调用,例如单击。

可能您正在尝试在页面加载时订阅用户,但在某些浏览器(如 Firefox 和 Safari)上这是不可能的,因为它被认为是用户的烦恼。

这就是为什么许多推送服务(如 OneSignal、Pushpad 等)建议使用双重选择加入的原因之一:首先显示使用 HTML/CSS 设计的订阅提示或按钮,然后单击按钮后,您实际上请求了许可(上面的代码)。


小智 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
        }
    });
});
Run Code Online (Sandbox Code Playgroud)

超文本标记语言

<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>
Run Code Online (Sandbox Code Playgroud)

加载网页后,这将打开一个弹出窗口,其中有 2 个按钮(/)。单击“是”,浏览器将询问是否允许通知。


小智 7

这也发生在我身上。如果您不想使用按钮或其他元素事件,您可以使用更高级别的文档单击事件并从那里请求权限。

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