This repository has been archived on 2023-12-07. You can view files and clone it, but cannot push or open issues or pull requests.
website/static/assets/scripts/detectlang.js
Sofía Aritz 6ec64b6d15 Add language detection
Check `navigator.language` and suggest going to that language's page.

This JS file is not required for the page to run, and the notices can easily be disabled using the button that is alongside the notice.

The status if the redirect notice is saved in localStorage under the `i18n:no_redirect_notice` key.
2023-04-20 23:02:49 +02:00

43 lines
1.5 KiB
JavaScript

const SPANISH_MESSAGE = "Versión en español"
const SPANISH_BUTTON = "No mostrar esto de nuevo"
const ENGLISH_MESSAGE = "English page"
const ENGLISH_BUTTON = "Do not show me this again"
if (redirect_notice_enabled()) {
let language = (navigator.language || navigator.userLanguage).split("-")[0]
if (location.pathname.startsWith("/en")) {
if (language === "es") {
add_redirect_notice(location.pathname.replace("/en", ""), SPANISH_MESSAGE, SPANISH_BUTTON)
}
} else if (!["weblog", "recommendations", "projects", "links"].includes(location.pathname.split("/")[1])) {
if (language !== "es") {
add_redirect_notice("/en" + location.pathname, ENGLISH_MESSAGE, ENGLISH_BUTTON)
}
}
}
function add_redirect_notice(redirect, message, btn_message) {
let main = document.getElementsByTagName("main").item(0)
let div = document.createElement("div")
div.classList.add("redirect-notice")
div.innerHTML = `<div><span>${message}:</span> <a href="${redirect}">${redirect}</a></div>`
let button = document.createElement("button")
button.addEventListener("click", () => {
disable_redirect_notice()
location.reload()
})
button.innerText = btn_message
div.append(button)
main.prepend(div)
}
function redirect_notice_enabled() {
return localStorage.getItem("i18n:no_redirect_notice") !== "1"
}
function disable_redirect_notice() {
localStorage.setItem("i18n:no_redirect_notice", "1")
}