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

71
Vistas
Set session key when user leaves page

I am trying to save a session key when user leaves the page here is the code for it, The use of the code is upon loading a page, you want to:

If this page was the last visited page: load its saved location else remove the last saved location and save it upon scrolling.

 const [scrollPosition, setScrollPosition] = React.useState('');

React.useEffect(() => {
    var pathName = document.location.pathname.substr(1);
    if (window) {
      window.onscroll = function (e) {
        setScrollPosition(window.scrollY);
      };
    }
  }, [scrollPosition]);

  if (typeof window !== "undefined") {
    window.addEventListener('unload', function(event) {
      if(scrollPosition != 0){
        const savedPosition = { position: scrollPosition, pathName };
        sessionStorage.setItem('scrollPosition', JSON.stringify(savedPosition));
      }
    }); 
  }

  React.useEffect(() => {
    var pathName = document.location.pathname.substr(1);
    const lastSavedPosition = JSON.parse(sessionStorage.getItem('scrollPosition'));
    if (window && lastSavedPosition && pathName === lastSavedPosition.pathName) {
       window.scrollTo(0, lastSavedPosition.position);
      console.log(`position_set to = ${lastSavedPosition.position}`);
    }
  }, []);
about 4 years ago · Juan Pablo Isaza
1 Respuestas
Responde la pregunta

0

I recommend you using localStorage instead of sessionStorage which is only persistent during one user session. When the user comes back, you won't have data available in the session storage to make it persistent use localStorage.

This thread contains a lot of well drafted answers check it, how to use localStorage and when to use it.

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