javascriptnavigationsingle-page-applicationonbeforeunload

How to distinguish between navigation and refresh page


I have single page app which has following URL pattern https://hostname/{organizationIdentifier}/#{pagePath}.

The app has implement some kind of "cache" based on sessionStorage.

When user switch organization context by navigating to different org (different organizationIdentifier in the URL) I want to trigger cache cleanup.

For this purpose I have implemented window.addEventLister("beforeunload", cleanCache). I have tried also navigation.addEventListener("navigate", navigateAction) but with no success.

But the cleanCache is triggered also on page refresh. How can I detect that the unload action will be followed with load action with same URL? How can I trigger cleanCache only on leaving app context or changing organization context?


Solution

  • In your very first JS (src/index.js or your root component):

    function getCurrentOrg() {
      const [, org] = window.location.pathname.split('/');
      return org;
    }
    
    function initOrgCache() {
      const currentOrg = getCurrentOrg();
      const lastOrg    = sessionStorage.getItem('activeOrg');
    
      if (lastOrg && lastOrg !== currentOrg) {
        sessionStorage.clear();
      }
    
      sessionStorage.setItem('activeOrg', currentOrg);
    }
    
    initOrgCache();
    

    Or for SPA

    import { useEffect } from 'react';
    import { useHistory }     from 'react-router-dom';
    
    function App() {
      const history = useHistory();
    
      useEffect(() => {
        const unlisten = history.listen((location) => {
          const newOrg = location.pathname.split('/')[1];
          const lastOrg = sessionStorage.getItem('activeOrg');
          if (newOrg !== lastOrg) {
            sessionStorage.clear();
            sessionStorage.setItem('activeOrg', newOrg);
          }
        });
        return () => unlisten();
      }, [history]);
    
      return (
        /* ... your app ... */
      );
    }