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
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
|
// 脚本位置: assets/js/ext-utils.js
/**
* 一些自定义的插件,通过AI进行的优化和增强
* @description 当前已有扩展
* @description 1. 快捷键绑定
* @description 2. 限制特定区域访问单页
* @version 2.0.0 优化版本
*/
// ==================== 配置常量 ====================
const CONFIG = {
// 移动设备检测断点 - 小于此宽度的设备被视为移动设备,将禁用快捷键功能
MOBILE_BREAKPOINT: 680,
// 缓存配置 - 用于存储用户国家信息,减少API调用
CACHE: {
COUNTRY_KEY: 'userCountry', // localStorage中存储国家代码的键名
COUNTRY_TIMESTAMP_KEY: 'userCountryTimestamp', // localStorage中存储时间戳的键名
EXPIRY_MS: 24 * 60 * 60 * 1000, // 缓存过期时间(24小时),超过此时间将重新获取国家信息
},
// API配置 - 用于获取用户地理位置信息
API: {
IPINFO_URL: 'https://ipinfo.io/json', // IP地理位置查询API地址,无需token的免费版本
TIMEOUT_MS: 5000, // 请求超时时间(毫秒),超过此时间将视为请求失败
RETRY_COUNT: 2, // 请求失败时的重试次数
RETRY_DELAY_MS: 1000, // 重试间隔时间(毫秒)
},
// DOM元素ID - 页面中需要操作的元素ID,确保与主题HTML结构匹配
DOM_IDS: {
SEARCH_TOGGLE: 'search-toggle-desktop', // 桌面端搜索切换按钮ID,用于打开搜索弹窗
SEARCH_INPUT: 'search-input-desktop', // 桌面端搜索输入框ID,用于接收用户输入
MASK: 'mask', // 遮罩层ID,用于关闭搜索弹窗
CONTENT: 'content', // 主要内容区域ID,用于显示访问限制消息
TOC_AUTO: 'toc-auto', // 自动目录容器ID,访问受限时需要隐藏
AREA_RESTRICTED: 'area-restricted', // 区域限制元素ID,包含受限国家列表的data属性
},
// 样式配置 - 访问限制消息的样式设置
STYLES: {
RESTRICTION_MESSAGE: {
minHeight: '180px', // 最小高度,确保消息框有足够空间
fontFamily: "'Segoe UI', 'Roboto', 'Helvetica Neue', Arial, sans-serif", // 字体栈,优先使用现代字体
backgroundColor: '#F8F8F8', // 背景颜色,柔和的浅灰色
border: '1px solid #bdc3c7', // 边框样式,柔和的灰色边框
borderRadius: '20px', // 圆角半径,较大的圆角使界面更友好
boxShadow: '0 8px 20px rgba(0, 0, 0, 0.1)', // 阴影效果,增加层次感
padding: '40px', // 内边距,确保内容有足够的呼吸空间
margin: '60px auto', // 外边距,上下60px,左右自动居中
maxWidth: 'min(85vw, 900px)', // 最大宽度,响应式设计,不超过视口85%或900px
transition: 'opacity 0.8s ease-out', // 透明度过渡动画,用于淡入效果
},
},
// 国家代码 - 特殊国家的ISO 3166-1 alpha-2代码
COUNTRIES: {
CHINA: 'CN', // 中国大陆国家代码,用于特殊处理(如显示备案信息、不加载外部分析脚本)
},
// 调试配置 - 控制调试信息的输出
DEBUG: {
ENABLED: true, // 是否启用调试日志,生产环境建议设为false以减少控制台输出
PREFIX: 'ExtUtils:', // 控制台日志前缀,便于识别来源和过滤日志
},
};
// ==================== 工具函数 ====================
const Utils = {
/**
* 调试日志输出
* @param {string} message - 日志消息
* @param {any} data - 可选数据
*/
log(message, data = null) {
if (CONFIG.DEBUG.ENABLED) {
console.debug(`${CONFIG.DEBUG.PREFIX} ${message}`, data);
}
},
/**
* 错误日志输出
* @param {string} message - 错误消息
* @param {Error} error - 错误对象
*/
logError(message, error = null) {
console.error(`${CONFIG.DEBUG.PREFIX} ${message}`, error);
},
/**
* 安全地设置localStorage
* @param {string} key - 键
* @param {string} value - 值
*/
safeSetLocalStorage(key, value) {
try {
localStorage.setItem(key, value);
} catch (error) {
this.logError('localStorage写入失败:', error);
}
},
/**
* 安全地获取localStorage
* @param {string} key - 键
* @returns {string|null} 值或null
*/
safeGetLocalStorage(key) {
try {
return localStorage.getItem(key);
} catch (error) {
this.logError('localStorage读取失败:', error);
return null;
}
},
/**
* 防抖函数
* @param {Function} func - 要防抖的函数
* @param {number} wait - 等待时间(毫秒)
* @returns {Function} 防抖后的函数
*/
debounce(func, wait) {
let timeout;
return function executedFunction(...args) {
const later = () => {
clearTimeout(timeout);
func(...args);
};
clearTimeout(timeout);
timeout = setTimeout(later, wait);
};
},
/**
* 安全地创建带超时的fetch请求
* @param {string} url - 请求URL
* @param {Object} options - 请求选项
* @param {number} timeout - 超时时间
* @returns {Promise} fetch Promise
*/
fetchWithTimeout(url, options = {}, timeout = CONFIG.API.TIMEOUT_MS) {
return Promise.race([
fetch(url, options),
new Promise((_, reject) =>
setTimeout(() => reject(new Error('请求超时')), timeout)
),
]);
},
/**
* 带重试机制的fetch请求
* @param {string} url - 请求URL
* @param {number} retryCount - 重试次数
* @returns {Promise} fetch Promise
*/
async fetchWithRetry(url, retryCount = CONFIG.API.RETRY_COUNT) {
try {
const response = await this.fetchWithTimeout(url);
if (!response.ok) {
throw new Error(`网络响应失败: ${response.status}`);
}
return await response.json();
} catch (error) {
if (retryCount > 0) {
this.log(`请求失败,${CONFIG.API.RETRY_DELAY_MS}ms后重试... 剩余重试次数: ${retryCount}`);
await new Promise(resolve => setTimeout(resolve, CONFIG.API.RETRY_DELAY_MS));
return this.fetchWithRetry(url, retryCount - 1);
}
throw error;
}
},
};
// ==================== 全局命名空间 ====================
if (typeof window.ExtUtils === 'undefined') {
window.ExtUtils = {};
}
// 检查并添加 isMobile 方法
if (typeof window.ExtUtils.isMobile !== 'function') {
window.ExtUtils.isMobile = function() {
return window.matchMedia(`only screen and (max-width: ${CONFIG.MOBILE_BREAKPOINT}px)`).matches;
};
}
// 检查并添加 getUserCountry 方法 (优化: Promise化和缓存)
if (typeof window.ExtUtils.getUserCountry !== 'function') {
window.ExtUtils.getUserCountry = function() {
return new Promise((resolve, reject) => {
const cachedCountry = Utils.safeGetLocalStorage(CONFIG.CACHE.COUNTRY_KEY);
const cachedTimestamp = Utils.safeGetLocalStorage(CONFIG.CACHE.COUNTRY_TIMESTAMP_KEY);
const now = Date.now();
// 检查缓存是否有效
if (cachedCountry && cachedTimestamp && (now - parseInt(cachedTimestamp, 10) < CONFIG.CACHE.EXPIRY_MS)) {
Utils.log('从缓存加载国家信息');
resolve(cachedCountry);
return;
}
// 从API获取国家信息
Utils.fetchWithRetry(CONFIG.API.IPINFO_URL)
.then(data => {
if (data?.country) {
// 验证国家代码格式(2个字母)
if (/^[A-Z]{2}$/i.test(data.country)) {
Utils.safeSetLocalStorage(CONFIG.CACHE.COUNTRY_KEY, data.country);
Utils.safeSetLocalStorage(CONFIG.CACHE.COUNTRY_TIMESTAMP_KEY, now.toString());
Utils.log('成功获取并缓存国家信息', data.country);
resolve(data.country.toUpperCase());
} else {
throw new Error(`无效的国家代码格式: ${data.country}`);
}
} else {
throw new Error('API返回数据不包含国家信息');
}
})
.catch(error => {
Utils.logError('国家信息请求失败:', error);
reject(null); // 拒绝Promise,但传递null表示获取失败
});
});
};
}
// ==================== 快捷键绑定类 ====================
class KeybindCustom {
static initKeyBind() {
// 缓存DOM元素引用
const elements = {
searchToggle: document.getElementById(CONFIG.DOM_IDS.SEARCH_TOGGLE),
searchInput: document.getElementById(CONFIG.DOM_IDS.SEARCH_INPUT),
mask: document.getElementById(CONFIG.DOM_IDS.MASK),
};
// 检查必要元素是否存在
if (!elements.searchToggle || !elements.searchInput) {
Utils.log('搜索元素不存在,跳过快捷键初始化');
return;
}
let isSearchActive = false;
// 检查当前焦点是否在输入元素中
const isInputFocused = () => {
const { activeElement } = document;
const tagName = activeElement?.tagName?.toLowerCase();
return activeElement === elements.searchInput ||
['textarea', 'input', 'pre'].includes(tagName);
};
// 处理键盘事件
const handleKeyDown = (event) => {
// 斜杠键:打开搜索
if (event.key === '/' && !isInputFocused()) {
event.preventDefault();
elements.searchToggle.click();
isSearchActive = true;
// 使用requestAnimationFrame确保DOM更新后再聚焦
requestAnimationFrame(() => {
elements.searchInput.focus();
});
}
// Escape键:关闭搜索
else if (event.key === 'Escape' && isSearchActive && elements.mask) {
elements.mask.click();
isSearchActive = false;
elements.searchInput.blur();
}
};
// 处理搜索输入框焦点事件
const handleSearchFocus = () => { isSearchActive = true; };
const handleSearchBlur = () => { isSearchActive = false; };
// 添加事件监听器
document.addEventListener('keydown', handleKeyDown);
elements.searchInput.addEventListener('focus', handleSearchFocus);
elements.searchInput.addEventListener('blur', handleSearchBlur);
Utils.log('快捷键绑定初始化完成');
}
}
// ==================== 访问限制类 ====================
class AccessRestriction {
constructor() {
// 缓存DOM元素引用
this.elements = {
areaAccessValidation: document.getElementById(CONFIG.DOM_IDS.AREA_RESTRICTED),
content: document.getElementById(CONFIG.DOM_IDS.CONTENT),
tocAuto: document.getElementById(CONFIG.DOM_IDS.TOC_AUTO),
};
// 解析受限国家列表
this.restrictedCountries = this.parseRestrictedCountries();
// 绑定方法上下文
this.hideBeianInfo = this.hideBeianInfo.bind(this);
}
/**
* 解析受限国家列表
* @returns {string[]} 受限国家代码数组
*/
parseRestrictedCountries() {
if (!this.elements.areaAccessValidation?.dataset.restrictedCountries) {
return [];
}
try {
return this.elements.areaAccessValidation.dataset.restrictedCountries
.split(',')
.map(country => country.trim().toUpperCase())
.filter(country => /^[A-Z]{2}$/.test(country));
} catch (error) {
Utils.logError('解析受限国家列表失败:', error);
return [];
}
}
/**
* 检查访问权限
* @param {string|null} country - 用户国家代码
*/
checkAccess(country) {
if (!country) {
Utils.log('未获取到国家信息,跳过访问控制');
return;
}
// 检查是否在受限国家列表中
if (this.elements.areaAccessValidation && this.restrictedCountries.includes(country)) {
Utils.log(`检测到受限国家: ${country}`);
this.displayRestrictionMessage();
this.hideTOCContent();
}
// 隐藏备案信息(非中国用户)
if (country !== CONFIG.COUNTRIES.CHINA) {
this.hideBeianInfo();
}
}
/**
* 显示访问限制消息
*/
displayRestrictionMessage() {
if (!this.elements.content) return;
// 创建访问限制消息内容
const restrictionContent = this.createRestrictionContent();
// 设置初始透明度为0,准备淡入动画
this.elements.content.style.opacity = '0';
this.elements.content.innerHTML = restrictionContent;
// 应用样式
this.applyRestrictionStyles();
// 触发淡入动画
requestAnimationFrame(() => {
setTimeout(() => {
this.elements.content.style.opacity = '1';
}, 100);
});
Utils.log('已显示访问限制消息');
}
/**
* 创建访问限制消息HTML内容
* @returns {string} HTML内容
*/
createRestrictionContent() {
return `
<div class="restriction-icon" role="img" aria-label="访问受限">🚫</div>
<h2 class="restriction-title">对不起,您所在的区域不允许访问该页面!</h2>
<p class="restriction-subtitle">请联系管理员以获取更多信息访问权限。</p>
`;
}
/**
* 应用访问限制样式
*/
applyRestrictionStyles() {
const styles = {
...CONFIG.STYLES.RESTRICTION_MESSAGE,
display: 'flex',
flexDirection: 'column',
justifyContent: 'center',
alignItems: 'center',
textAlign: 'center',
boxSizing: 'border-box',
};
// 应用容器样式
Object.assign(this.elements.content.style, styles);
// 添加内部元素样式
this.addInternalStyles();
}
/**
* 添加内部元素样式
*/
addInternalStyles() {
const styleId = 'ext-utils-restriction-styles';
// 检查是否已添加样式
if (document.getElementById(styleId)) return;
const style = document.createElement('style');
style.id = styleId;
style.textContent = `
.restriction-icon {
font-size: 1.5em;
margin-bottom: 20px;
color: #7f8c8d;
}
.restriction-title {
margin: 0;
font-size: 1.4em;
font-weight: 600;
color: #34495e;
}
.restriction-subtitle {
margin-top: 15px;
font-size: 1em;
color: #95a5a6;
}
`;
document.head.appendChild(style);
}
/**
* 隐藏目录内容
*/
hideTOCContent() {
if (!this.elements.tocAuto) return;
Array.from(this.elements.tocAuto.children)
.filter(child => child.nodeType === Node.ELEMENT_NODE)
.forEach(child => {
child.style.display = 'none';
});
Utils.log('已隐藏目录内容');
}
/**
* 隐藏备案信息
*/
hideBeianInfo() {
const beianElements = document.querySelectorAll('.footer-line.beian');
beianElements.forEach(element => {
element.style.display = 'none';
});
if (beianElements.length > 0) {
Utils.log(`已隐藏 ${beianElements.length} 个备案信息元素`);
}
}
}
// ==================== Vercel分析类 ====================
class VercelInsights {
static isLoaded = false;
/**
* 初始化Vercel Insights
* @param {string|null} country - 用户国家代码
*/
static init(country) {
// 只为非中国用户加载,且避免重复加载
if (!country || country === CONFIG.COUNTRIES.CHINA || this.isLoaded) {
Utils.log(`跳过Vercel Insights加载: 国家=${country}, 已加载=${this.isLoaded}`);
return;
}
try {
// 初始化Vercel Analytics全局函数
window.va = window.va || function() {
(window.vaq = window.vaq || []).push(arguments);
};
// 创建并加载脚本
const script = document.createElement('script');
script.defer = true;
script.src = '/_vercel/insights/script.js';
script.onerror = () => Utils.logError('Vercel Insights脚本加载失败');
script.onload = () => {
this.isLoaded = true;
Utils.log('Vercel Insights脚本加载成功');
};
document.head.appendChild(script);
} catch (error) {
Utils.logError('初始化Vercel Insights失败:', error);
}
}
}
// ==================== 初始化逻辑 ====================
class ExtUtilsInitializer {
static async init() {
try {
Utils.log('开始初始化ExtUtils扩展');
// 1. 初始化快捷键(仅桌面端)
if (!window.ExtUtils.isMobile()) {
KeybindCustom.initKeyBind();
} else {
Utils.log('移动设备,跳过快捷键初始化');
}
// 2. 等待DOM完全加载
await this.waitForDOMReady();
// 3. 获取用户国家信息
const userCountry = await this.getUserCountrySafely();
// 4. 初始化访问限制
// markdown 配置示例: <div id="area-restricted" data-restricted-countries="CN,SG" style="display:none;"></div>
const accessRestriction = new AccessRestriction();
accessRestriction.checkAccess(userCountry);
// 5. 初始化Vercel Insights(此项配置用于站点部署在Vercel,启用Vercel Analytics后的兼容调整)
VercelInsights.init(userCountry);
Utils.log('ExtUtils扩展初始化完成');
} catch (error) {
Utils.logError('ExtUtils初始化失败:', error);
}
}
/**
* 等待DOM准备就绪
* @returns {Promise<void>}
*/
static waitForDOMReady() {
return new Promise(resolve => {
if (document.readyState === 'loading') {
document.addEventListener('DOMContentLoaded', resolve, { once: true });
} else {
resolve();
}
});
}
/**
* 安全地获取用户国家信息
* @returns {Promise<string|null>} 国家代码或null
*/
static async getUserCountrySafely() {
try {
const country = await window.ExtUtils.getUserCountry();
Utils.log(`成功获取用户国家: ${country}`);
return country;
} catch (error) {
Utils.logError('获取用户国家信息失败:', error);
return null;
}
}
}
// ==================== 自动初始化 ====================
// 使用立即执行异步函数进行初始化
(async () => {
await ExtUtilsInitializer.init();
})();
|