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

时间:2018-02-15 13:13:01

标签: javascript function push-notification notifications web-push

我遇到一个问题,即某个函数在较新的浏览器中更改了它的实现。我想按照实现相应地调用函数。

Notification.requestPermission().then(function (permission) {...})

以前称之为,

Notification.requestPermission(callback);

我正在调用最初的方式,因此在旧浏览器中它会破坏,因为它们的实现中不会返回承诺。

2 个答案:

答案 0 :(得分: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);
    }
}());

答案 1 :(得分:0)

我们可以为旧的Safari浏览器做一个包装,迫使它们返回Promise

const notificationRequestPermission = () => {
  return new Promise(Notification.requestPermission);
};

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