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

如何在JavaScript中向重定向目标页面传递用户名与密码

Solution for Passing URL Credentials to Redirect Target Page

Got it, let's tackle this problem. Your custom barcode reader appends the username and password directly to the initial page's URL (like https://bob:redpaRrot93@www.acme.com/redir.html), and you need to pass those exact credentials to the redirect target page without hardcoding them.

Here's a robust, dynamic solution that avoids hardcoding and leverages browser-native URL parsing:

Step-by-Step Implementation

First, we'll extract the credentials from the current URL using the browser's built-in location object, then build the redirect URL dynamically.

function redirectToContent() {
  // Pull username and password directly from the current URL's auth segment
  const username = location.username;
  const password = location.password;

  // Quick check to avoid invalid redirects if credentials are missing
  if (!username || !password) {
    console.error("No authentication credentials found in the URL");
    return;
  }

  // Define your target page's base address (update this to your actual target)
  const targetBase = "www.micron-engineering.gq/ppages/404.html";

  // Build the full redirect URL with credentials, matching the current protocol
  if (location.protocol === "https:") {
    window.location = `https://${username}:${password}@${targetBase}`;
  } else {
    window.location = `http://${username}:${password}@${targetBase}`;
  }
}

// Trigger the redirect when the page loads (adjust this to your desired trigger)
window.addEventListener('load', redirectToContent);

Key Improvements Over Your Hardcoded Version

  • Dynamic Credential Extraction: Using location.username and location.password is far more reliable than manual URL parsing or hardcoding. These browser-native properties directly pull the auth values from the URL's user:pass@host segment.
  • Cleaner URL Construction: Template strings (``) eliminate the need for messy escape sequences like \x3A\x2F\x2F—you can write the URL naturally.
  • Error Prevention: The quick credential check stops the function from running if no credentials are present, avoiding broken redirects.

Important Notes

  • Browser Security Restrictions: Keep in mind that modern browsers may hide the password in the address bar or restrict HTTP Basic Auth via URL for security reasons. This works for your specific use case, but for long-term solutions, consider more secure auth methods (like token-based authentication) if possible.
  • Server Support: Ensure your target server supports HTTP Basic Auth, otherwise the credentials won't be recognized and you'll hit access issues.

内容的提问来源于stack exchange,提问作者Massimo Manca

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.14 08:38:19