Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading