Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

66
Views
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 answers
Answer question

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 Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!