Skip to content

Commit 48eaa38

Browse files
feat(mdn-web-docs): 跟随网页更新,新增语言切换按钮
1 parent 5cec2af commit 48eaa38

File tree

2 files changed

+48
-6
lines changed

2 files changed

+48
-6
lines changed

src/scripts-header/mdn-web-docs.js

+1-1
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,7 @@
11
module.exports = isProd =>
22
`// ==UserScript==
33
// @name MDN 文档辅助
4-
// @version 1.0.0
4+
// @version 1.1.0
55
// @description 在提供切换中文语言的页面自动切换为中文
66
// @author sakura-flutter
77
// @namespace https://github.com/sakura-flutter/tampermonkey-scripts

src/scripts/mdn-web-docs/index.js

+47-5
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,11 @@
11
import { $ } from '@/utils/selector'
22
import { warn } from '@/utils/log'
33

4+
const docsLang = matchLang(location.pathname)
5+
const supports = getSupports()
6+
warn(docsLang)
7+
warn(supports)
8+
49
function main() {
510
window.addEventListener('click', event => {
611
// 标记是否自行切换语言
@@ -9,19 +14,52 @@ function main() {
914
}
1015
}, true)
1116

12-
const docsLang = matchLang(location.pathname)
13-
warn(docsLang)
17+
changeLang()
18+
addLangButton()
19+
}
20+
21+
function changeLang() {
1422
if (isChinese(docsLang)) return
1523
// 是否自行切换过语言
1624
if (sessionStorage.getItem('hand-control-language') === 'true') return
1725

18-
const supports = getSupports()
19-
warn(supports)
2026
for (const item of supports) {
2127
isChinese(matchLang(item)) && location.replace(item)
2228
}
2329
}
2430

31+
function addLangButton() {
32+
const values = [] // 中英 排序
33+
for (const item of supports) {
34+
const lang = matchLang(item)
35+
if (isChinese(lang)) {
36+
values[0] = item
37+
} else if (isEnglish(lang)) {
38+
values[1] = item
39+
}
40+
}
41+
warn(values)
42+
if (values.length < 2) return
43+
44+
const a = document.createElement('a')
45+
a.innerText = '中-英'
46+
a.href = isChinese(docsLang) ? values[1] : values[0]
47+
a.classList.add('button')
48+
a.style = [
49+
'position: fixed',
50+
'right: 0',
51+
'bottom: 15vh',
52+
'min-height: auto',
53+
'padding: 0px 2px',
54+
'font-size: 12px',
55+
'letter-spacing: 2px',
56+
].join(';')
57+
a.onclick = function() {
58+
sessionStorage.setItem('hand-control-language', true)
59+
}
60+
document.body.append(a)
61+
}
62+
2563
function matchLang(str) {
2664
// 匹配 pathname 或字符串
2765
// /en-US/docs/Web/API/ 或 en-us
@@ -32,8 +70,12 @@ function isChinese(lang) {
3270
return /zh-cn/i.test(lang)
3371
}
3472

73+
function isEnglish(lang) {
74+
return /en-US/i.test(lang)
75+
}
76+
3577
function getSupports() {
36-
return [...$('#select_language').options].map(opt => opt.value)
78+
return [...$('#language-selector').options].map(opt => opt.value)
3779
}
3880

3981
main()

0 commit comments

Comments
 (0)