You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Framework7登录页跳转问题求助:LocalStorage校验及登录后跳转失效

Hey there! Let's work through your redirect issue step by step — I’ve seen this exact problem a bunch of times, so let’s break it down and get it fixed.

Problem Analysis & Solutions

First: Nail the Initial LocalStorage Check Logic

Let's start with the core startup behavior. We need to check LocalStorage as soon as the page loads, and redirect if the target variable exists. Here's the solid base code:

// Add this to your entry page (like index.html) inside a <script> tag
window.addEventListener('DOMContentLoaded', function() {
  // Replace 'authToken' with your actual variable name
  const storedAuthData = localStorage.getItem('authToken');
  
  if (storedAuthData) {
    // Redirect immediately if the variable exists
    window.location.href = 'page2.html';
    return;
  }
  
  // If not present, let the login form stay visible (or unhide it if you had it hidden)
  // Example: document.getElementById('login-form').classList.remove('hidden');
});

Next: Fix the Login Success Redirect Failure

If window.location.href isn't working after login, it's almost always one of these common issues — let's troubleshoot each:

1. You’re Not Blocking Form Default Behavior

If your login button is inside a <form> tag, the browser will default to reloading the page when you submit, which cuts off your redirect code. Fix this by stopping the default form submission:

// Bind to your login form's submit event
document.getElementById('login-form').addEventListener('submit', function(e) {
  // Stop the browser's default page reload
  e.preventDefault();
  
  // Get your login input values
  const username = document.getElementById('username').value;
  const password = document.getElementById('password').value;
  
  // Replace this with your actual validation logic
  if (username && password) {
    // Save the authenticated state to LocalStorage
    localStorage.setItem('authToken', 'your-valid-auth-identifier');
    // Now redirect safely
    window.location.href = 'page2.html';
  } else {
    alert('Please fill in all login fields');
  }
});

2. Incorrect File Path

Double-check that page2.html is in the right location relative to your login page:

  • If it's in the same folder: 'page2.html' works fine
  • If it's in a subfolder: Use 'pages/page2.html' (adjust the path to match your structure)
  • For root-level paths: Use '/page2.html' (this points to the website's root directory)

3. Async Login Requests Need Proper Waiting

If you’re using an API call for login (async operation), you must wait for the request to succeed before redirecting. Don’t run the redirect synchronously:

// Example with async/await for API login
document.getElementById('login-btn').addEventListener('click', async function() {
  const username = document.getElementById('username').value;
  const password = document.getElementById('password').value;
  
  try {
    const response = await fetch('/api/login', {
      method: 'POST',
      body: JSON.stringify({ username, password }),
      headers: { 'Content-Type': 'application/json' }
    });
    
    if (response.ok) {
      const authData = await response.json();
      localStorage.setItem('authToken', authData.token);
      // Only redirect AFTER the async request succeeds
      window.location.href = 'page2.html';
    } else {
      alert('Login failed — check your credentials');
    }
  } catch (error) {
    console.error('Login request error:', error);
    alert('Login request failed — please try again later');
  }
});

4. Debug with Console Logs

If you’re still stuck, add logs to verify what’s happening:

// Add these lines right before your redirect
console.log('Stored LocalStorage value:', localStorage.getItem('authToken'));
console.log('Redirect path:', 'page2.html');
window.location.href = 'page2.html';

Open your browser’s DevTools (F12) → Console tab to check if the values match what you expect. Also, check the Application tab to confirm the variable is actually saved to LocalStorage.

Full Working Example (index.html)

Here’s a complete, self-contained example to test with:

<!DOCTYPE html>
<html>
<head>
  <title>Login Page</title>
  <style>
    .hidden { display: none; }
  </style>
</head>
<body>
  <div id="login-form">
    <h2>Please Log In</h2>
    <form>
      <div>
        <label>Username:</label>
        <input type="text" id="username" required>
      </div>
      <div>
        <label>Password:</label>
        <input type="password" id="password" required>
      </div>
      <button type="submit">Log In</button>
    </form>
  </div>

  <script>
    // Check LocalStorage on page load
    window.addEventListener('DOMContentLoaded', function() {
      const authToken = localStorage.getItem('authToken');
      if (authToken) {
        window.location.href = 'page2.html';
      }
    });

    // Handle login form submission
    document.querySelector('form').addEventListener('submit', function(e) {
      e.preventDefault();
      
      const username = document.getElementById('username').value;
      const password = document.getElementById('password').value;
      
      // Dummy validation — replace with your real logic
      if (username === 'demo' && password === 'demo123') {
        localStorage.setItem('authToken', 'valid-demo-token');
        console.log('Login successful, redirecting...');
        window.location.href = 'page2.html';
      } else {
        alert('Invalid username or password');
      }
    });
  </script>
</body>
</html>

内容的提问来源于stack exchange,提问作者Raffaele Colleo

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.26 09:02:06