Repository navigation
Expand file tree
/
Copy pathcontent.js
More file actions
272 lines (237 loc) · 8.36 KB
/
Copy pathcontent.js
File metadata and controls
272 lines (237 loc) · 8.36 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
// content.js
// 配置选择器
const SELECTORS = {
tweetText: '[data-testid="tweetText"]',
actionBar: '[role="group"]',
article: 'article',
}
// 中文检测正则
const CHINESE_REGEX = /[\u4e00-\u9fa5]/
// 图标 SVG (简单的翻译图标)
const TRANSLATE_ICON = `
<svg viewBox="0 0 24 24" aria-hidden="true" class="x-translate-icon">
<g><path d="M12 2C6.48 2 2 6.48 2 12s4.48 10 10 10 10-4.48 10-10S17.52 2 12 2zm-1 17.93c-3.95-.49-7-3.85-7-7.93 0-.62.08-1.21.21-1.79L9 15v1c0 1.1.9 2 2 2v1.93zm6.9-2.54c-.26-.81-1-1.39-1.9-1.39h-1v-3c0-.55-.45-1-1-1H8v-2h2c.55 0 1-.45 1-1V7h2c1.1 0 2-.9 2-2v-.41c2.93 1.19 5 4.06 5 7.41 0 2.08-.8 3.97-2.1 5.39z"></path></g>
</svg>
`
const GOOGLE_ICON_SVG = `
<svg viewBox="0 0 24 24" class="x-google-icon-svg">
<path d="M12.48 10.92v3.28h7.84c-.24 1.84-.853 3.187-1.787 4.133-1.147 1.147-2.933 2.4-6.053 2.4-4.827 0-8.6-3.893-8.6-8.72s3.773-8.72 8.6-8.72c2.6 0 4.507 1.027 5.907 2.347l2.307-2.307C18.747 1.44 16.133 0 12.48 0 5.867 0 .533 5.333.533 12S5.867 24 12.48 24c3.44 0 6.147-1.133 8.213-3.293 2.067-2.067 2.72-5.067 2.72-7.467 0-.747-.053-1.467-.16-2.147H12.48z" fill="#4285F4"></path>
</svg>
`
function init() {
const observer = new MutationObserver(mutations => {
for (const mutation of mutations) {
if (mutation.type === 'childList') {
processTweets()
}
}
})
observer.observe(document.body, {
childList: true,
subtree: true,
})
// 初始处理
processTweets()
}
function processTweets() {
const articles = document.querySelectorAll(SELECTORS.article)
articles.forEach(article => {
if (article.dataset.xTranslateProcessed) return
const textNode = article.querySelector(SELECTORS.tweetText)
if (!textNode) return // 没有文本的推文(如仅图片)忽略
const text = textNode.innerText
// 优先使用 lang 属性进行判断
const lang = textNode.getAttribute('lang')
if (lang) {
// 如果明确标记为中文 (zh, zh-CN, zh-TW, etc),则跳过
if (lang.startsWith('zh')) {
article.dataset.xTranslateProcessed = 'true'
return
}
// 如果标记为非中文,则不进行正则检查,直接通过
} else {
// 如果没有 lang 属性,降级使用正则检测
// 如果包含中文,则跳过
if (CHINESE_REGEX.test(text)) {
article.dataset.xTranslateProcessed = 'true'
return
}
}
// 找到操作栏 (评论、转发、点赞)
const actionBar = article.querySelector(SELECTORS.actionBar)
if (!actionBar) return
// 注入按钮
injectTranslateButton(textNode, text)
article.dataset.xTranslateProcessed = 'true'
})
}
function injectTranslateButton(textNode, text) {
// 创建按钮容器
const btnContainer = document.createElement('div')
btnContainer.className =
'css-1dbjc4n r-18u37iz r-1h0z5md r-13awgt0 x-translate-btn-container'
btnContainer.setAttribute('role', 'button')
btnContainer.setAttribute('tabindex', '0')
// 带图标的按钮
btnContainer.innerHTML = `
<div class="x-translate-btn-inner">
${TRANSLATE_ICON}
<span class="x-translate-text">翻译推文</span>
</div>
`
// 绑定点击事件
btnContainer.addEventListener('click', async e => {
e.stopPropagation() // 防止触发推文点击
const label = btnContainer.querySelector('.x-translate-text')
if (label.innerText === '正在翻译...') return
// 检查是否已有翻译结果
const existingResult = textNode.parentElement.querySelector(
'.x-translation-result',
)
const article = textNode.closest(SELECTORS.article)
const currentText =
(textNode && typeof textNode.innerText === 'string'
? textNode.innerText
: text) || ''
const lastText = article ? article.dataset.xTranslateLastText || '' : ''
if (existingResult) {
if (currentText && lastText && currentText !== lastText) {
existingResult.remove()
} else {
// 如果已有结果,则进行收起/展开切换
if (existingResult.style.display === 'none') {
existingResult.style.display = 'block'
label.innerText = '收起翻译'
} else {
existingResult.style.display = 'none'
label.innerText = '查看翻译'
}
return
}
}
const originalText = label.innerText
label.innerText = '正在翻译...'
const {text: anchorMaskedText, anchors} = textNode
? maskAnchors(textNode)
: {text: text || '', anchors: []}
const {text: maskedText, urls} = maskUrls(anchorMaskedText)
try {
const response = await chrome.runtime.sendMessage({
action: 'translate',
text: maskedText,
})
if (response && response.translatedText) {
const safeTranslatedText = escapeHtml(response.translatedText)
const withUrls = unmaskUrls(safeTranslatedText, urls)
const finalHtml = unmaskAnchors(withUrls, anchors)
renderTranslation(textNode, finalHtml)
if (article) {
article.dataset.xTranslateLastText = currentText
}
label.innerText = '收起翻译'
} else {
label.innerText = '翻译失败'
setTimeout(() => (label.innerText = originalText), 2000)
}
} catch (err) {
console.error('Translation error:', err)
label.innerText = '错误'
setTimeout(() => (label.innerText = originalText), 2000)
}
})
// 插入到正文下方
textNode.insertAdjacentElement('afterend', btnContainer)
}
function maskUrls(text) {
const urls = []
// 匹配 http:// 或 https:// 开头,直到遇到空白字符
// 使用稍微复杂的正则来避免匹配到 URL 后面的中文
const maskedText = text.replace(
/(https?:\/\/[a-zA-Z0-9\-\._~:\/\?#\[\]@!$&'\(\)\*\+,;=%]+)/g,
match => {
// 处理末尾标点 (虽然上面的正则已经比较严格,但双重保险)
let url = match
let suffix = ''
// 常见标点符号在 URL 结尾通常不是 URL 的一部分
const trailing = /[.,!?。,!?]$/
if (trailing.test(match)) {
const m = match.match(trailing)
suffix = m[0]
url = match.slice(0, -m[0].length)
}
urls.push(url)
// 使用特殊的占位符,两侧加空格防止粘连
return ` __X_TRANSLATE_URL_${urls.length - 1}__ ${suffix}`
},
)
return {text: maskedText, urls}
}
function maskAnchors(container) {
const anchors = []
const walk = node => {
if (node.nodeType === Node.TEXT_NODE) {
return node.textContent || ''
}
if (node.nodeType !== Node.ELEMENT_NODE) {
return ''
}
if (node.tagName && node.tagName.toLowerCase() === 'a') {
anchors.push(node.outerHTML)
return ` __X_TRANSLATE_ANCHOR_${anchors.length - 1}__ `
}
let result = ''
node.childNodes.forEach(child => {
result += walk(child)
})
return result
}
return {text: walk(container), anchors}
}
function unmaskAnchors(text, anchors) {
return text.replace(
/__\s*X_TRANSLATE_ANCHOR_(\d+)\s*__/gi,
(match, index) => {
const anchor = anchors[parseInt(index)]
if (!anchor) return match
return anchor
},
)
}
function unmaskUrls(text, urls) {
// 恢复 URL 链接
// 允许占位符中间可能有空格 (Google 翻译可能会把 _ 分开)
return text.replace(/__\s*X_TRANSLATE_URL_(\d+)\s*__/gi, (match, index) => {
const url = urls[parseInt(index)]
if (!url) return match
return `<a href="${url}" target="_blank" rel="noopener noreferrer" class="x-translation-link">${url}</a>`
})
}
function escapeHtml(text) {
return text
.replace(/&/g, '&')
.replace(/</g, '<')
.replace(/>/g, '>')
.replace(/"/g, '"')
.replace(/'/g, ''')
}
function renderTranslation(textNode, htmlContent) {
// 检查是否已经存在翻译结果
const existing = textNode.parentElement.querySelector('.x-translation-result')
if (existing) {
existing.remove()
}
const resultDiv = document.createElement('div')
resultDiv.className = 'x-translation-result'
resultDiv.setAttribute('dir', 'auto')
resultDiv.innerHTML = `
<div class="x-translation-header">
${GOOGLE_ICON_SVG}
<span>Google 翻译</span>
</div>
<div class="x-translation-content">${htmlContent}</div>
`
// 插入到原文下方
textNode.parentElement.appendChild(resultDiv)
}
// 启动
init()