根据其实现在不同的浏览器版本上使用 Notification.requestPermission
Use Notification.requestPermission on different browser versions as per it's implementation
我遇到了一个问题,一个函数的实现在较新的浏览器中发生了变化。我想根据实现相应地调用函数。
Notification.requestPermission().then(function (permission) {...})
以前这样称呼,
Notification.requestPermission(callback);
我调用的是初始方式,因此在较旧的浏览器中它被破坏了,因为在它们的实现中没有返回承诺。
正在拍摄这个。看来您需要使用标志有条件地触发函数。
// 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);
}
}());
我们可以为旧的 safari 浏览器制作一个包装器,强制它们 return a Promise
:
const notificationRequestPermission = () => {
return new Promise(Notification.requestPermission);
};
// Usage
notificationRequestPermission().then(console.log)
我遇到了一个问题,一个函数的实现在较新的浏览器中发生了变化。我想根据实现相应地调用函数。
Notification.requestPermission().then(function (permission) {...})
以前这样称呼,
Notification.requestPermission(callback);
我调用的是初始方式,因此在较旧的浏览器中它被破坏了,因为在它们的实现中没有返回承诺。
正在拍摄这个。看来您需要使用标志有条件地触发函数。
// 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);
}
}());
我们可以为旧的 safari 浏览器制作一个包装器,强制它们 return a Promise
:
const notificationRequestPermission = () => {
return new Promise(Notification.requestPermission);
};
// Usage
notificationRequestPermission().then(console.log)