根据不同浏览器版本的实现,使用Notification.requestPermission。

4
我遇到了一个问题,即某个函数在新的浏览器中实现发生了更改。我想根据实现方式相应地调用该函数。
Notification.requestPermission().then(function (permission) {...})

这个之前被称为:

Notification.requestPermission(callback);

我一直使用的是初始方式,在旧版浏览器中会出现问题,因为它们的实现中没有返回承诺。


我认为你应该将标题改为询问你感兴趣的具体函数,而不是现在的通用函数。 - Jonathon Reinhart
Done @JonathonReinhart - Saba
这可能会帮助您解决问题 - https://developer.mozilla.org/zh-CN/docs/Web/API/Notifications_API/Using_the_Notifications_API - fabfas
并非如此,他们已经展示了使用废弃的方法。 - Saba
2个回答

1
尝试解答。看起来您需要有一个带有标志的条件函数触发。
// Outer function to prevent scope pollution
(function(){
    function thingThatINeed() {}
    // Flag to keep track of whether it is called.
    var isCalled = false;
    function conditionalCall(){
       if(!isCalled) {
           // if the conditionalCall function is called more than once, the 
           // needed function will still only be called once.
           thingThatINeed();
           isCalled = true;
       }
    }
    // Call requestPermission with the deprecated form
    var promise = Notification.requestPermission(conditionalCall);

    // if a promise is returned, then use the promise.
    if(promise){
        promise.then(conditionalCall);
    }
}());

0
我们可以为旧版Safari浏览器创建一个包装器,强制它们返回一个Promise:
const notificationRequestPermission = () => {
  return new Promise(Notification.requestPermission);
};

// Usage
notificationRequestPermission().then(console.log)

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