Created
December 20, 2025 09:49
-
-
Save bulletinmybeard/6a6934ee7ee7c2d3738d9643542d8db7 to your computer and use it in GitHub Desktop.
Userscript - URL Rewriter
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| // ==UserScript== | |
| // @name URL Rewriter | |
| // @namespace https://rschu.me/ | |
| // @version 1.0.0 | |
| // @description Rewrites URLs from one domain to another on the fly | |
| // @author Bulletinmybeard | |
| // @match *://app.external.example.com/* | |
| // @run-at document-end | |
| // @grant none | |
| // ==/UserScript== | |
| (function () { | |
| 'use strict'; | |
| const SOURCE_URL = 'https://app.internal.example.com'; | |
| const TARGET_URL = 'https://app.external.example.com'; | |
| const REWRITE_ATTRIBUTES = ['href', 'src', 'action', 'data-url', 'data-href']; | |
| const rewriteElement = (el) => { | |
| for (const attr of REWRITE_ATTRIBUTES) { | |
| const val = el.getAttribute(attr); | |
| if (val && val.includes(SOURCE_URL)) { | |
| el.setAttribute(attr, val.replaceAll(SOURCE_URL, TARGET_URL)); | |
| } | |
| } | |
| if (el.childNodes.length === 1 && el.childNodes[0].nodeType === Node.TEXT_NODE) { | |
| const txt = el.textContent; | |
| if (txt.includes(SOURCE_URL)) { | |
| el.textContent = txt.replaceAll(SOURCE_URL, TARGET_URL); | |
| } | |
| } | |
| }; | |
| const rewriteDOM = () => { | |
| document.querySelectorAll('*').forEach(rewriteElement); | |
| }; | |
| const observer = new MutationObserver((mutations) => { | |
| for (const mutation of mutations) { | |
| for (const node of mutation.addedNodes) { | |
| if (node.nodeType === Node.ELEMENT_NODE) { | |
| rewriteElement(node); | |
| node.querySelectorAll('*').forEach(rewriteElement); | |
| } | |
| } | |
| } | |
| }); | |
| const initObserver = () => { | |
| observer.observe(document.body, { | |
| childList: true, | |
| subtree: true, | |
| }); | |
| }; | |
| rewriteDOM(); | |
| if (document.body) { | |
| initObserver(); | |
| } else { | |
| new MutationObserver((_, obs) => { | |
| if (document.body) { | |
| obs.disconnect(); | |
| initObserver(); | |
| } | |
| }).observe(document.documentElement, { childList: true }); | |
| } | |
| })(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment