Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Userscript: Redirect Website to its English Version
// This userscript redirects you to the English version of a website if it's denoted in the source code.
// Insert any URLs of websites below (after @match), for example https://developer.mozilla.org/* or https://www.php.net/*
// Use multiple @match clauses to enable the script on several domains.
// ==UserScript==
// @name Redirect to English
// @namespace http://tampermonkey.net/
// @version 1.0
// @description Redirect websites to their English version
// @author Florian Reuschel <florian@loilo.de>
// @match [INSERT URL HERE]
// @grant none
// ==/UserScript==
if (document.documentElement.lang !== 'en') {
const referrerHost = document.referrer
? new URL(document.referrer).hostname
: undefined
const currentHost = new URL(location.href).hostname
if (
// Don't redirect when directly calling the page
referrerHost !== undefined &&
// Don't redirect if coming from another page on the same domain
referrerHost !== currentHost &&
// Don't redirect if history state indicates that this page has previously been
// redirected away from (to maintain ability to go back to the original language)
!(history.state && history.state.redirectToEnglish)
) {
const englishLink = document.head.querySelector('link[rel="alternate"][hreflang="en"]')
if (englishLink) {
history.replaceState({ redirectToEnglish: true }, null)
location.assign(englishLink.href)
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.