1

I've found this comment to match what I'm looking for. It seems to work, for me, perfectly with "console.log". I want to know when a user has left the page:

const getChatRoomId = () => {}

useEffect(() => {
  const chatRoomId = getChatRoomId()

  if (chatRoomId) {
    console.log('----HAS ENTERED /messages/* ------', chatRoomId)
  }

  // I believe this is not important?
  const routeChangeStart = url => {}

  // This is very important
  const beforeunload = e => {
    if (chatRoomId) {
      console.log(`---- IS LEAVING /messages/${chatRoomId} ------`)
    }
  }

  window.addEventListener('beforeunload', beforeunload);
  Router.events.on('routeChangeStart', routeChangeStart);

  return () => {
    window.removeEventListener('beforeunload', beforeunload);
    Router.events.off('routeChangeStart', routeChangeStart);
  };
}, [someStateChangeVariable])

The above works great but using a function inside beforeunload does not work. I've made some searches and one states to "return a string":


[..]

// This is very important
  const beforeunload = e => {
    if (chatRoomId) {
      alert(`---- IS LEAVING /messages/${chatRoomId} ------`)
    }
    
    return 'GoodBye!'
  }

[..]

Blocked alert('---- IS LEAVING /messages/1 ------') during beforeunload.

I'm using NextJs catch all routes /pages/[...messages] where you can have a page id of "new" or "123" where "123" is the message id and "new" to create a new message. How to trigger a function when a user leaves a page?

Sylar
  • 11,422
  • 25
  • 93
  • 166

1 Answers1

0

You can use router.events methods: NextJS docs.

Also this topic might be relevant.

Roland Rácz
  • 2,879
  • 3
  • 18
  • 44