jaidedctrl / IPFS Redirection

// ==UserScript==
// @name        IPFS Redirection
// @description Redirect IPFS sites (and gateways) to custom gateway.
// @author	jaidedctrl
// @license GPL-3.0-or-later; http://www.gnu.org/licenses/gpl-3.0.txt
// @match	https://*
// @match	http://*
// @run-at      document-start
// ==/UserScript==

// !! EDIT THIS LINE TO CHANGE YOUR GATEWAY
var ipfsRoot = "https://gateway.xwx.moe";

var isAtRoot = null;
var isAtRoot = window.location.href.match( ipfsRoot + ".*" );

// =====================================
// GATEWAY URLS (.../ipfs/...)
// =====================================
// just check if it has /ip.s/ in it haha
function gateway_check ( ) {
	var ipfsPath = window.location.href.match( "/ipfs/.*|/ipns/.*");

	if ( ipfsPath != null  &&  ipfsPath.length == 1  &&  isAtRoot == null ) {
		window.location = ipfsRoot + ipfsPath[0];
	}
}

// =====================================
// GATEWAY-BACKED SITES (e.g., ipfs.io)
// =====================================
// for these we have to check if the X-Ipfs-Path header is present
function site_check ( ) {
	var request = new XMLHttpRequest();
	request.open( 'HEAD', document.location, false );
	request.send( null );

	var headers = request.getAllResponseHeaders().toLowerCase();
	var ipfsHeaders = headers.match( "x-ipfs-path: .*" );

	if ( ipfsHeaders != null  &&  ipfsHeaders.length == 1  &&  isAtRoot == null ) {
		ipfsPath = ipfsHeaders[0].replace( "x-ipfs-path: ", "" );
		window.location = ipfsRoot + ipfsPath;
	}
}

// =====================================
// INVOCATION
// =====================================
if ( isAtRoot == null ) {
	gateway_check();
	site_check();
}