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

如何通过JavaScript将网站所有死链重定向至指定页面?

Got it, let's work through this problem—you need to redirect broken internal links to your custom 404-error-page.html both when working locally (file:// protocol) and once the site goes live. Your current code has a couple of gaps (like the undefined result variable) and doesn't account for local file restrictions, so let's break down practical solutions.

Why Your Current Code Isn't Working

  • The result variable is never initialized or populated—there's no logic to check if the link is broken in the first place.
  • Local file environments (file://) block HTTP requests (like fetch/XHR) due to browser security rules, so any attempt to check link status via those methods will fail locally.

Solution 1: Temporary Local-Friendly Fix (Known Unfinished Pages)

If you know exactly which pages haven't been built yet, this is the simplest approach for local development. Just maintain a list of incomplete paths and redirect clicks on those links:

// List all internal links that don't have corresponding HTML files yet
const unfinishedPages = [
  "random-link-directing-to-a-non-existing-page",
  "about-us.html",
  "products/featured.html"
  // Add other dead paths here
];

// Attach click handlers to all internal links
document.querySelectorAll('a').forEach(link => {
  link.addEventListener('click', function(event) {
    const targetHref = this.getAttribute('href');
    
    // Skip external links (http/https//)
    if (targetHref.startsWith('http') || targetHref.startsWith('//')) {
      return;
    }

    // Check if the link points to an unfinished page
    if (unfinishedPages.includes(targetHref)) {
      event.preventDefault();
      window.location.href = '404-error-page.html';
    }
  });
});

Pros:

  • Works perfectly locally (no HTTP requests needed)
  • Lightweight and easy to update as you finish pages
  • No browser security issues to worry about

Solution 2: Universal Fix (Local + Online)

For a solution that works everywhere, we'll split logic based on whether we're in a local file environment or a live server:

document.querySelectorAll('a').forEach(link => {
  link.addEventListener('click', async function(event) {
    const targetHref = this.getAttribute('href');
    
    // Skip external links
    if (targetHref.startsWith('http') || targetHref.startsWith('//')) {
      return;
    }

    let isBroken = false;
    const isLocalEnvironment = window.location.protocol === 'file:';

    if (isLocalEnvironment) {
      // Local mode: use our unfinished pages list
      const unfinishedPages = [
        "random-link-directing-to-a-non-existing-page",
        // Add other dead paths here
      ];
      isBroken = unfinishedPages.includes(targetHref);
    } else {
      // Online mode: check link status with a lightweight HEAD request
      try {
        const response = await fetch(targetHref, { 
          method: 'HEAD', 
          mode: 'same-origin' 
        });
        // Mark as broken if the response isn't successful (404, 500, etc.)
        isBroken = !response.ok;
      } catch (error) {
        // If the request fails (e.g., network issue), treat it as broken
        isBroken = true;
      }
    }

    if (isBroken) {
      event.preventDefault();
      window.location.href = '404-error-page.html';
    }
  });
});

Key Notes:

  • Local Environment: We rely on the unfinished pages list since HTTP checks are blocked.
  • Online Environment: Using a HEAD request instead of GET is more efficient—it only fetches the response headers, not the entire page content.
  • Edge Cases: This handles same-origin internal links (which is what your use case specifies). External links are ignored entirely.

Bonus: Server-Side Backup

Once you go live, add a server-side custom 404 configuration as a backup. For example:

  • Nginx: Add error_page 404 /404-error-page.html; to your config
  • Apache: Use ErrorDocument 404 /404-error-page.html in your .htaccess

This ensures that even if the JavaScript fails (e.g., a user has JS disabled), visitors still see your custom 404 page instead of the browser's default.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.04.29 17:27:43