Home > Mobile >  I want to remove cookies when the browser is closed but keep them while navigating between pages. Ho
I want to remove cookies when the browser is closed but keep them while navigating between pages. Ho

Time:10-20

Hy, I want to delete all the cookies and local storage when closing the browser but want to keep the cookies and local storage while navigating between pages in nextjs. I am using window.onbeforeunload event but this event is also triggered on navigating between pages. How to handle this issue.

CodePudding user response:

As others have mentioned in comments you probably should use sessionStorage. See Window sessionStorage for more information. Cool thing about it is that it deletes data after the session ends. But you can also delete session data within the session if you wish.

Edit: You could handle cookie and local storage data deletion on your own (when the browser is closed). Do this after you've stored whatever you need in sessionStorage. Then when you navigate around you'll still have that data in sessionStorage regardless of whether cookies or ls have it.

CodePudding user response:

It's solved. The method I'm using is I'm checking if the sessionStorage is active then don't call the handleAllSessions function to remove the cookies otherwise call it.

    if (
    typeof window !== 'undefined' &&
    !sessionStorage.getItem('sessionActive')
  ) {
    handleAllSessions();
  }
  function handleAllSessions() {
    if (!sessionStorage.getItem('sessionActive')) {
      document.cookie = 'suauth=; expires=2000-10-16T19:22:35.000Z;';
      localStorage.removeItem('isAuthenticated');
    }
  }
  • Related