angular - Firebase 网络推送通知不起作用
问题描述
我已经为我的 PWA ionic 4 应用程序配置了网络推送通知。The web push notifications are working like a charm when the tab is switched ie in background or other than my app.
The issue is when the tab is active I get the push messaging inside application section of chrome inspection but there is no notification fired.
下面是代码:
app.component.ts
async ngOnInit() {
firebase.initializeApp(environment.firebase);
}
ngAfterViewInit() {
this.platform.ready().then(async () => {
await this.notificationsService.requestPermission();
});
}
通知服务.ts
export class NotificationsService {
init(): Promise<void> {
return new Promise<void>((resolve, reject) => {
navigator.serviceWorker.ready.then(
registration => {
// Don't crash an error if messaging not supported
if (!firebase.messaging.isSupported()) {
resolve();
return;
}
const messaging = firebase.messaging();
// Register the Service Worker
messaging.useServiceWorker(registration);
// Initialize your VAPI key
messaging.usePublicVapidKey(environment.firebase.vapidKey);
// Listen to messages when your app is in the foreground
messaging.onMessage(payload => {
console.log("Payload is here", payload);
});
// Optional and not covered in the article
// Handle token refresh
messaging.onTokenRefresh(() => {
messaging
.getToken()
.then((refreshedToken: string) => {
console.log(refreshedToken);
})
.catch(err => {
console.error(err);
});
});
resolve();
},
err => {
reject(err);
}
);
});
}
因此,如果应用程序选项卡在 chrome 中打开,则触发通知时应该console.log
在内部调用messaging.onMessage
但它不会被执行。我在. _firebase-messaging-sw.js
解决方案
当您的应用程序在前台时,您的应用程序将不会收到messaging
可观察的通知,但它会在messages
可观察的情况下发出。
所以你应该像这样订阅它
firebase.messages.subscribe((message: any) => {
if (message.notification) {
// Show your notification from here
}
});
推荐阅读
- python - 如何将不同 csv 文件中的两列合并为一个 csv 文件
- html - 如何让 Safari 正确显示我的 Google 字体?
- oop - 关闭在失败的构造函数中创建的资源
- elasticsearch - ElasticSearch 中每个字段的不同时间范围
- android - 膨胀类 androidx.fragment.app.FragmentContainerView 时出错
- java - 添加maven依赖后获取Classdefnotfound异常
- python - Python:格式化 json 输出
- python - 按值范围将 Pandas DataFrame 复制到多个文件中
- google-chrome - 我正在尝试解析这个 json 我不知道我在这里做错了什么
- mysql - 使用 mvc 架构连接到 node.js 项目中的 MySql