我有 NextJS PWA 应用程序,并使用 VAPID 和 web-push (nodejs) 配置了它。该通知会在所有其他设备(android、web、mac safari)上弹出,但不会在带有 safari 的 iPhone 上弹出。
额外细节:
奇怪的是我确实收到了推送事件。所以worker.js工作正常。但问题是显示弹出窗口时,例如自我注册.showNotification。我尝试了很多事情,但一直坚持这个。
还有其他人经历过吗?
======== 代码详情如下
这就是我的 next.config.js 的配置方式:
const isDev = process.env.NODE_ENV === 'development'
const withPWA = require('next-pwa')( {
dest: "public",
sw: "sw.js",
register: true,
skipWaiting: true,
disable: isDev
});
const nextConfig = {
reactStrictMode: true,
};
module.exports = withPWA(nextConfig);
我如何设置 VAPID 详细信息:
webpush.setVapidDetails(
"mailto:[email protected]",
vapidKeys.publicKey,
vapidKeys.privateKey
);
这就是我的worker.js 的样子:
self.addEventListener("push", async (e) => {
try {
const { message, body, icon } = JSON.parse(e.data.text());
// Notify the main thread to play sound
const clients = await self.clients.matchAll();
clients.forEach(client => {
client.postMessage({
type: 'PLAY_SOUND'
});
});
e.waitUntil(
self.registration.showNotification(message)
);
} catch (error) {
// Send error log to the main thread
self.clients.matchAll().then(clients => {
clients.forEach(client => {
client.postMessage({
type: 'ERROR',
message: `Error in push event: ${error.message}`
});
});
});
}
});
self.addEventListener("notificationclick", (event) => {
event.preventDefault()
event.notification.close();
event.waitUntil(
self.clients.matchAll({
type: "window",
}).then((clientList) => {
for (const client of clientList) {
if (client.url === "/" && "focus" in client)
return client.focus();
}
if (clients.openWindow) return clients.openWindow("/");
})
);
});
我尝试过两种不同的 iPhone 设备。我已经在 android 上尝试过(有效),在 mac os 上也尝试过(有效)。
我尝试在 iOS 上调试 Safari 上下文。我可以看到 sw.js 已正确加载,并且控制台日志正常工作(它甚至触发了我用来调试的自定义事件)
但我认为问题在于
showNotification
,我不明白为什么。
您的公共文件夹中需要有一个
manifest.json
文件。另外,不要忘记将其添加到您的layout.tsx文件的head标签中。
我这里有该应用程序的工作版本。
代码: https://github.com/david-randoll/push-notification-nextjs
现场演示: https://push-notification.davidrandoll.com/
别忘了在 iPhone 上
Add to home
。