0

I had this idea of using navigator.sendBeacon() to call a cloud function to update a certain document. Why I am using navigator.sendBeacon(), is because I thought I could combine it with an event listener as such:

document.addEventListener("visibilitychange", () => {
    if (document.visibilityState === "hidden") {
      navigator.sendBeacon(
        "https://us-central1-company.cloudfunctions.net/functionHere"
      );
    }
});

So I want it to be called when the tab/browser is closed. However, currently, this isn't working. Is there an alternative way to do this? Because I want to update my Firestore document when a user closes his/her tab/browser.

The error that I am getting is as such:

{
  "textPayload": "Request has incorrect Content-Type. ",
  "insertId": "...",
  "resource": {
    "type": "cloud_function",
    "labels": {
      "function_name": "functionHere",
      "project_id": "company",
      "region": "us-central1"
    }
  },
  "timestamp": "2022-10-11T06:38:12.047495Z",
  "severity": "WARNING",
  "labels": {
    "execution_id": "...",
    "instance_id": "..."
  },
  "logName": "...",
  "trace": "...",
  "receiveTimestamp": "2022-10-11T06:38:12.060954110Z"
}
Owenn
  • 638
  • 1
  • 6
  • 23
  • Unrelated to your error, but have you considered using the beforeunload event instead? https://developer.mozilla.org/en-US/docs/Web/API/Window/beforeunload_event – Jet.B.Pope Oct 11 '22 at 19:31
  • @Jet.B.Pope `beforeunload` event triggers a confirmation dialog which I do not want at all. I want it to be executed immediately at the moment the browser/tab is closed. – Owenn Oct 12 '22 at 06:20
  • if you return undefined it won't do that. See this answer for details: https://stackoverflow.com/a/29627642/9063088 – Jet.B.Pope Oct 12 '22 at 13:21

0 Answers0