[英]Push API: Mobile browsers don't receive push notifications anytime. Only when SW is running
我正在使用 node.js 开发 PWA。 它是可安装的并且运行良好。
最近我尝试实现推送通知,如下所述: https://developer.mozilla.org/en-US/docs/Web/Progressive_web_apps/Re-engageable_Notifications_Push
这是为所有订阅触发通知的快捷方式(仅用于测试目的)
app.get('/notifyall/', function(req, res) {
subscriptions.forEach(subObject => {
webPush.sendNotification(subObject.sub, "notify All");
})
res.send("sent");
});
这是 serviceworker 中的事件处理程序
self.addEventListener('push', function(event) {
const payload = event.data ? event.data.text() : 'no payload';
console.debug("sw push event");
event.waitUntil(
self.registration.showNotification('ServiceWorker Cookbook', {
body: payload,
renotify: true,
tag: 'test'
})
);
});
这就是我注册推送服务订阅的方式
sub = navigator.serviceWorker.ready
.then(function(registration)
{
return registration.pushManager.getSubscription()
.then(async function(subscription)
{
console.debug("pwasetup: getSubscription");
if (subscription) {
console.debug("sub found");
sub = subscription;
return subscription;
}
const response = await fetch('/vapidPublicKey/');
const vapidPublicKey = await response.text();
// Chrome doesn't accept the base64-encoded (string) vapidPublicKey yet
const convertedVapidKey = frontendfuncs.urlBase64ToUint8Array(vapidPublicKey);
var newSub = registration.pushManager.subscribe({
userVisibleOnly: true,
applicationServerKey: convertedVapidKey
});
console.debug("sub: " + JSON.stringify(newSub));
return newSub;
});
})
.then(function(subscription)
{
// Send the subscription details to the server using the Fetch API.
console.debug("sub: " + JSON.stringify(subscription));
Notification.requestPermission(function(result)
{
if(result === "granted")
{
fetch('/register/', {
method: 'post',
headers: {
'Content-type': 'application/json'
},
body: JSON.stringify({
subscription: subscription
}),
});
}
})
});
});
我在Chrome、Firefox 和 Internet (Samsung)的三星 Galaxy S10+ 上测试了使用三种不同的移动浏览器接收推送通知。 (当然在我的app的installed/A2HS版本中。推送通知是由上面提到的/notifyall/路由中的代码触发的)
当应用程序打开时,或者软件仍在运行 state 时,收到并显示通知没有任何问题。 但在那之后,Android 和三星互联网的 Chrome 中的事情变得不那么容易了:
Chrome:在应用程序关闭后 2 分钟触发通知,直到我再次打开 PWA 后才会显示通知。 (奖励问题:为什么 2 分钟后?我认为 chrome 会在 30 秒后关闭 sw)
互联网(三星):软件停止后,通知到达显示解锁。 不是更早。
Firefox:似乎随时都能收到推送通知并按原样显示。
有谁知道,Chrome 和三星互联网的问题是什么? 我只想随时通知我的用户。 不是在某些情况下...
谢谢!
问题解决了。 比听起来容易...
由于需要安装 PWA/A2HS 才能使用随时接收通知的功能,所以我尝试将所有需要的设置都交给 PWA 本身(允许通知、禁用后台优化等)。
因此我从来没有想过,也禁用浏览器主应用的后台优化,这是唤醒 PWA 的 serviceworker 所必需的。
所有三个浏览器现在都按预期工作。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.