404 to Archive Redirecter

Detects 404/Not Found pages and redirects to the archived version on archive.org

You will need to install an extension such as Tampermonkey, Greasemonkey or Violentmonkey to install this script.

You will need to install an extension such as Tampermonkey or Violentmonkey to install this script.

You will need to install an extension such as Tampermonkey or Violentmonkey to install this script.

You will need to install an extension such as Tampermonkey or Userscripts to install this script.

You will need to install an extension such as Tampermonkey to install this script.

You will need to install a user script manager extension to install this script.

(I already have a user script manager, let me install it!)

You will need to install an extension such as Stylus to install this style.

You will need to install an extension such as Stylus to install this style.

You will need to install an extension such as Stylus to install this style.

You will need to install a user style manager extension to install this style.

You will need to install a user style manager extension to install this style.

You will need to install a user style manager extension to install this style.

(I already have a user style manager, let me install it!)

// ==UserScript==
// @name         404 to Archive Redirecter
// @namespace    http://tampermonkey.net/
// @version      0.2
// @description  Detects 404/Not Found pages and redirects to the archived version on archive.org
// @author       Patryk Kordisch
// @match        *://*/*
// @run-at       document-end
// @exclude      *://web.archive.org/*
// @grant        none
// @license MIT
// ==/UserScript==

(function() {
    'use strict';

    function is404Page() {

        // Check HTTP Status Code using Performance API
        const navEntries = window.performance.getEntriesByType('navigation');
        if (navEntries.length > 0 && navEntries[0].responseStatus === 404) {
            return true;
        }
        return false;
    }


    // Confirmation dialog
    function offerRedirect(archiveUrl) {
        if (confirm(`This appears to be a missing page.\n\nWould you like to view an archived version?`)) {
            window.location.href = archiveUrl;
        }
    }


    // If the current page qualifies as a 404 and user confirms it, he gets redirected to the archive
    setTimeout(() => {
        if (is404Page()) {
            // Get URL
            const currentUrl = window.location.href;
            const archiveUrl = "https://web.archive.org/web/" + currentUrl;

            setTimeout(() => offerRedirect(archiveUrl), 500);
        }
    }, 2000);

})();