Sha*_*ath 5 javascript angularjs firebase firebase-cloud-messaging
我在我的 angular 应用程序中使用 firebase 在 web 中发送推送通知。我实现messaging.onMessage()
了当应用程序在前台和messaging.setBackgroundMessageHandler()
应用程序在后台时接收通知。我收到通知没有任何问题,但我需要根据收到的通知更新值. 我可以在使用时进行更新,messaging.onMessage()
但在使用messaging.setBackgroundMessageHandler()
. 如果我可以在本地存储接收到的值并在我的应用程序中获取它,即使它也可以。
我在很多地方都对此进行了研究,但找不到任何解决方案。有人可以帮我弄这个吗?谢谢!
importScripts('https://www.gstatic.com/firebasejs/3.5.2/firebase-app.js');
importScripts('https://www.gstatic.com/firebasejs/3.5.2/firebase-messaging.js');
var config = {
apiKey: "MY_API_KEY",
authDomain: "MY_AUTH_DOMAIN",
databaseURL: "MY_DB_URL",
storageBucket: "URL",
messagingSenderId: "VALID_ID"
};
firebase.initializeApp(config);
const messaging = firebase.messaging();
messaging.setBackgroundMessageHandler(function(payload) {
console.log('[firebase-messaging-sw.js] Received background message ', payload);
return self.registration.showNotification("Title", {body: 'New notification.',})
});
Run Code Online (Sandbox Code Playgroud)
经过几天的搜索,找到了一个 Github 页面,其中包含该问题的解决方案。
您可以做的是获取窗口客户端列表,该列表将返回您的源的选项卡列表,然后向每个窗口客户端发布消息。(此代码位于setBackgroundMessageHandler()
)。
获取页面列表的方法是:
const promiseChain = clients.matchAll({
type: 'window',
includeUncontrolled: true
})
.then((windowClients) => {
for (let i = 0; i < windowClients.length; i++) {
const windowClient = windowClients[i];
windowClient.postMessage(data);
}
})
.then(() => {
return registration.showNotification('my notification title');
});
return promiseChain;
Run Code Online (Sandbox Code Playgroud)
然后要在页面中接收消息,请添加一个侦听器,如下所示:
navigator.serviceWorker.addEventListener('message', function(event) {
console.log('Received a message from service worker: ', event.data);
});
Run Code Online (Sandbox Code Playgroud)
非常感谢在 Github 上做出贡献的人。如需更多参考,请访问
希望对你们有所帮助。如果您在实施过程中遇到任何疑问,请Ping或评论我。
归档时间: |
|
查看次数: |
901 次 |
最近记录: |