【问题标题】:Notification.requestPermission() throwing error on MozillaNotification.requestPermission() 在 Mozilla 上抛出错误
【发布时间】:2020-08-11 23:43:06
【问题描述】:

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

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

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

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

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

【问题讨论】:

    标签: mozilla web-push


    【解决方案1】:

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

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

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

    【讨论】:

    • @JaberKibria 确实是我说的...您需要在回调中请求click 或其他用户触发事件的权限
    【解决方案2】:

    这段代码对我有用:

    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>
    

    这将在使用 2 个按钮(Yes/No)加载网页后打开一个弹出窗口。点击Yes,浏览器会询问是否允许通知。

    【讨论】:

      【解决方案3】:

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

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

      【讨论】:

      • 在第一次点击后删除该事件处理程序可能是个好主意
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2010-12-03
      • 2017-10-02
      • 1970-01-01
      • 1970-01-01
      • 2016-11-02
      相关资源
      最近更新 更多