Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

262
Vistas
Call server side function before unload (firebase)

I'm trying to save user data when the JavaScript event "beforeunload" is triggered. I call a server-side function (firebase cloud functions) that simply gets an object from the user and updates a document. The function does trigger, but from the firebase console I can see it finished with code 204. Here is my client code

window.onbeforeunload = function() {
    firefun_ref(data);
}

Server side:

exports.updateStats = functions.https.onCall(async (data, context) => {
  return admin.firestore().collection("stats")
    .doc((new Date()).toISOString().substring(0, 10))
    .update(filter(data));
});

I want to point out that if I run the function by itself it works fine, it just gives problems when it's in the before unload event

about 4 years ago · Juan Pablo Isaza
3 Respuestas
Responde la pregunta

0

This will not be possible.

Browsers severely limit what you're allowed to do in a beforeunload event, because it's so prone to abuse. Asynchronous events are not allowed (because they could force the window to stay open for an arbitrary amount of time after the user wants to close it.)

As far as I know, the only reliable usage of onbeforeunload is to display a prompt allowing the user to change their mind; some browsers will let you customize the text that appears (by returning a string from the beforeunload handler), some browsers will always show default text:

window.addEventListener('beforeunload', function (e) {
  // Cancel the event
  e.preventDefault(); // If you prevent default behavior in Mozilla Firefox prompt will always be shown
  // Chrome requires returnValue to be set
  e.returnValue = '';
});

https://developer.mozilla.org/en-US/docs/Web/API/WindowEventHandlers/onbeforeunload

about 4 years ago · Juan Pablo Isaza Denunciar

0

I am trying to get this to work with Beacon API and even found a hook:

/*
  see https://developer.mozilla.org/en-US/docs/Web/API/Navigator/sendBeacon
  
  ```jsx
  const MyComponent = ({ children }) => {
    // will get fired if the page unloads while the component is mounted
    useUnloadBeacon({
      url: 'https://api.my.site/route',
      payload: () => {
        return 'something'
      }
    })
    
    return children
  }
  ```
*/

import { useEffect } from "react"

export const useUnloadBeacon = ({
  url = "",
  payload = () => {},
}) => {
  const eventHandler = () => navigator.sendBeacon(url, payload())

  useEffect(() => {
    window.addEventListener("unload", eventHandler, true)
    return () => {
      window.removeEventListener("unload", eventHandler, true)
    }
  }, [])
}

The only problem I am facing is triggering the cloud function. I am sending a get request but it is somehow not triggering.

Cloud function

app.post("/setStatusToOpen", setStatusToOpen)

const setStatusToOpen = async (req, res) => {
  console.log("setStatusToOpen, req.query", req.query)
  const { documentId } = req.query
  try {
    const setPayload = { status: "open" }
    firestore
      .doc(`messageInABottle/${documentId}`)
      .set(setPayload, { merge: true })

    return res.send(true)
  } catch (error) {
    console.log("Error in getMessageInABottleRecipient:", error)
    return res.send(error)
  }
}

I think it has something to do with the headers not being right.

about 4 years ago · Juan Pablo Isaza Denunciar

0

If the data you want to write is known before the user closes the tab, you can register a so-called onDisconnect handler in the Realtime Database (the other database that is part of Firebase).

An onDisconnect handler is a delayed write operation that runs as soon as the server notices that the client has disconnected, either because the SDK in that client tells it before disconnecting, or because the socket times out on the server (which may take a few minutes).

No equivalent exists on Firestore, because its wire protocol is connectionless, while Realtime Database works based on (web) sockets. If you want to integrate this into Firestore though, have a look at the documentation on building a presence system in Firestore by using the Realtime Database.

about 4 years ago · Juan Pablo Isaza Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda