javascript 将Service Worker中的数据写入Cloud Firestore

izkcnapc  于 9个月前  发布在  Java
关注(0)|答案(2)|浏览(107)

我正在处理一个Firebase项目,我想在我的JavaScript项目的service worker中接收Firebase云消息(从Node.js服务器发送)。这工作正常,但现在我想在收到通知后从我的service worker中保存一些数据在我的Firebase云firestore中。还有问题,我在下面列出的错误中运行:
未捕获的引用错误:XMLHttpRequest未在Ln.(xmlhttp.js:167)在Me(channelrequest.js:512)在Ce(webchannelbase.js:1249)在Kn.xa(webchannelbase.js:1251)在re(run.js:124)定义
由于几天来我试图找到错误,但无法找到解决方案,直到现在.因此,我希望你能帮助我现在.我已经尝试保存数据在firebase实时数据库工作,但因为我需要有离线持久化,我不得不切换到云firestore运行在上面的错误.
下面是我的node.js服务器发送通知的代码(userID和registrationToken在前面定义):

payload = {
     data: {
     "title": "This is a Notification",
     "body": "This is the body of the notification message."
     },
};

options = {
     priority: "high",
     timeToLive: 7200
};

// send message to the registration token
admin.messaging().sendToDevice(registrationToken, payload, options).then(function(response) {
     admin.firestore().collection("Logging").doc(userID).set({active: "true"});
}).catch(function(error) {
     console.log("Error sending message:", error);
});

字符串
下面是在我的firebase-messagins service worker文件中接收通知的代码(userID在前面定义):

self.addEventListener('notificationclick', function(event) {
  event.notification.close();
  const keepAlive = async() => {
      firebase.firestore().collection("Logging").doc(userID).update({"open": "true"}); 
  }
  event.waitUntil(keepAlive()); 
});


有人能帮我吗?我没有更多的想法来解决我的问题:/

fjnneemd

fjnneemd1#

你不能在service worker中使用XMLHttpRequest,而是需要使用Fetch API
根据您的代码,是Firebase客户端库在底层使用了XMLHttpRequest。我不认为您对此有任何控制权(至少根据我在Firebase当前JavaScript文档中看到的内容)。
你可以尝试直接使用REST API,而不是在service worker中使用Firebase客户端库,使用fetch()发送HTTP请求。你将负责身份验证和设置客户端库将为你处理的任何用户ID等,但我认为这是你在service worker中的最佳选择。

dzhpxtsq

dzhpxtsq2#

从版本9开始,Firebase Web SDK使用fetch而不是XMLHttpRequest。所以它在服务工作者中工作。

相关问题