Skip to content

Commit 78cf784

Browse files
authored
Add language redirection script to en docs optimize the language switching function. (#6443)
1 parent 98dd95e commit 78cf784

File tree

2 files changed

+64
-0
lines changed

2 files changed

+64
-0
lines changed
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,63 @@
1+
(function () {
2+
const userSelectedLang = localStorage.getItem("userSelectedLang");
3+
const currentPath = window.location.pathname;
4+
5+
if (userSelectedLang) {
6+
if (userSelectedLang === "en" && !currentPath.startsWith("/en/")) {
7+
const newPath = "/en" + (currentPath === "/" ? "" : currentPath);
8+
window.location.replace(newPath);
9+
return;
10+
} else if (userSelectedLang === "zh" && currentPath.startsWith("/en/")) {
11+
const newPath = currentPath.replace(/^\/en/, "") || "/";
12+
window.location.replace(newPath);
13+
return;
14+
}
15+
return;
16+
}
17+
18+
const userLang = (
19+
navigator.language ||
20+
navigator.userLanguage ||
21+
"en"
22+
).toLowerCase();
23+
const langPrefix = userLang.split("-")[0];
24+
25+
if (langPrefix === "zh") {
26+
if (currentPath.startsWith("/en/")) {
27+
const newPath = currentPath.replace(/^\/en/, "") || "/";
28+
window.location.replace(newPath);
29+
}
30+
} else {
31+
if (!currentPath.startsWith("/en/")) {
32+
const newPath = "/en" + (currentPath === "/" ? "" : currentPath);
33+
window.location.replace(newPath);
34+
}
35+
}
36+
})();
37+
38+
document.addEventListener("click", function (event) {
39+
const langSwitcher = event.target.closest(".md-select__link[hreflang]");
40+
if (langSwitcher) {
41+
event.preventDefault();
42+
43+
const newLang = langSwitcher.getAttribute("hreflang");
44+
localStorage.setItem("userSelectedLang", newLang);
45+
46+
const currentPath = window.location.pathname;
47+
let newPath;
48+
49+
if (newLang === "en") {
50+
newPath = currentPath.startsWith("/en/")
51+
? currentPath
52+
: "/en" + (currentPath === "/" ? "" : currentPath);
53+
} else {
54+
newPath = currentPath.startsWith("/en/")
55+
? currentPath.replace(/^\/en/, "") || "/"
56+
: currentPath;
57+
}
58+
59+
const queryAndHash = window.location.search + window.location.hash;
60+
61+
window.location.href = newPath + queryAndHash;
62+
}
63+
});

docs/en/mkdocs.yml

+1
Original file line numberDiff line numberDiff line change
@@ -184,6 +184,7 @@ extra:
184184
# Customization Javascript
185185
extra_javascript:
186186
- /stylesheets/zoom_image.js
187+
- /stylesheets/language-redirect.js
187188
# - https://cdn.jsdelivr.net/npm/mermaid/dist/mermaid.min.js # disable fix mermaid not working
188189

189190
# Customization css

0 commit comments

Comments
 (0)