run_the_race
run_the_race

Reputation: 2358

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

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>

Upvotes: 1

Views: 189

Answers (2)

Mohit Sharma
Mohit Sharma

Reputation: 648

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);
  }

Upvotes: 0

run_the_race
run_the_race

Reputation: 2358

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>

Upvotes: 2

Related Questions