Home > database >  Javascript: Modern working approach to refresh the page redirects to another location
Javascript: Modern working approach to refresh the page redirects to another location

Time:12-11

I have tried some answers on SO, but they are old and no longer work, or are blocked by the browser.

I have a login, and a separate login failed page (separate for a good reason, please don't say make them the same page).

If the user is shown the failed login page, and they hit refresh, I would like to go to the login page, not refresh the failed login page.

Existing answers go something like this:

<script type="module">
    function redirect()
    {
        window.location.href="/login/";
        return true;
    }
    window.addEventListener('beforeunload', redirect);
</script>

CodePudding user response:

Not ideal, but instead of catching the reload before navigating away, catch the reload at the start of the page:

Reload detection code from: https://stackoverflow.com/a/53307588/5506400

<script type="module">
    const pageAccessedByReload = (
    (window.performance.navigation && window.performance.navigation.type === 1) ||
        window.performance
        .getEntriesByType('navigation')
        .map((nav) => nav.type)
        .includes('reload')
    );
    if (pageAccessedByReload) {
        window.location.href="/login/";
    }
</script>

CodePudding user response:

let me know this will help or not, use type value to check for reload

  // Use getEntriesByType() to just get the "navigation" events
  var entries = performance.getEntriesByType('navigation');

  for (var i = 0; i < entries.length; i  ) {
    console.log('= Navigation entry['   i   ']');
    var p = entries[i];
    // dom Properties
    console.log(
      'DOM content loaded = '  
        (p.domContentLoadedEventEnd - p.domContentLoadedEventStart)
    );
    console.log('DOM complete = '   p.domComplete);

    // other properties
    console.log('type = '   p.type);
  }

  • Related