Skip to content

Instantly share code, notes, and snippets.

@e-t-l
Forked from loilo/redirect-to-english.js
Created December 1, 2022 17:36
Show Gist options
  • Save e-t-l/b1ab83d14b894da10d90e697775098cb to your computer and use it in GitHub Desktop.
Save e-t-l/b1ab83d14b894da10d90e697775098cb to your computer and use it in GitHub Desktop.
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 <[email protected]>
// @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