0

I want a function, to send a request to a server (don't care about response) before a user refreshes the page.

I've tried using the componentWillUnmount approach but the page refresh doesn't call this function. e.g.

import React, { useEffect } from 'react';

const ComponentExample => () => {
    useEffect(() => {
        return () => {
            // componentWillUnmount in functional component.
            // Anything in here is fired on component unmount.
            // Call my server to do some work
        }
    }, []) }

Does anyone have any ideas how to do this?

2 Answers2

3

You could try listening for the window.beforeunload event.

The beforeunload event is fired when the window, the document and its resources are about to be unloaded. The document is still visible and the event is still cancelable at this point.

useEffect(() => {
  const unloadCallback = (event) => { ... };

  window.addEventListener("beforeunload", unloadCallback);
  return () => window.removeEventListener("beforeunload", unloadCallback);
}, []);

Note: This will respond to anything that causes the page to unload though.

Note 2:

However note that not all browsers support this method, and some instead require the event handler to implement one of two legacy methods:

  • assigning a string to the event's returnValue property
  • returning a string from the event handler.
Drew Reese
  • 165,259
  • 14
  • 153
  • 181
  • Perfect. That's what I was looking for. For anyone looking here, I had to add a line to the call back: `unloadCallBack = e => { // do work delete e['returnValue'] }` – greenlamponatable Nov 23 '20 at 13:52
  • 1
    It's advisable you use `beforeunload` instead of `unload` – Joshua Nov 23 '20 at 15:14
  • @Joshua Thanks. In my testing I didn't notice a difference between the two, but upon reading the official docs I agree. – Drew Reese Nov 23 '20 at 16:37
  • @DrewReese For the `unloadCallback` function, if it returned a `e.returnValue = "Are you sure?"`, this would produce an alert with two options: "Cancel" and "Leave". If the user selects "Leave", do you know how to call some function, say `someFunction()`, right before the page refreshes? [This is a bit of an indirectly related question to the OP!] – penguin Aug 12 '22 at 23:11
  • @penguin Not that I'm aware of currently. I think the idea is to either do the work in the `unloadCallback`, or ask the user what they want to do, and if they choose leave then the browser manages the resources. In other words, `unloadCallback` ***is*** that "some function". Browser maintainers have made it clear they don't want pages to keep users around any longer than they need to when users have indicated they want to leave. No more Columbo style ["but hey, just one more thing..."](https://www.youtube.com/watch?v=vYgUPD2khtw) nag screens. – Drew Reese Aug 12 '22 at 23:23
0

You can do this, almost, by checking if the page has been refreshed.

Source: https://developer.mozilla.org/en-US/docs/Web/API/Navigation_timing_API

Example:

if (window.performance) {
  console.info("window.performance is supported");
  console.info(performance.navigation.type);

  if (performance.navigation.type == performance.navigation.TYPE_RELOAD) {
    console.info( "This page is reloaded" );
  } else {
    console.info( "This page is not reloaded");
  }
}
Tomas
  • 1,001
  • 8
  • 16