mohのAI正在绞尽脑汁想思路ING···
mohのAI摘要
mohのAI-Lite

想让你的博客首页更加个性化,为访客提供更友好的体验吗?本教程将教你如何在 Hexo Butterfly 主题中实现一个智能的访客欢迎卡片,可以根据访问者的地理位置、距离、时间等信息,显示独特的欢迎问候。

一、创建欢迎卡片结构

1.1、在主题目录下创建卡片模板文件

1
[BlogRoot]\themes\butterfly\layout\includes\widget\card_welcome.pug

写入以下内容

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
.card-widget.card-welcome
.item-headline
i.fa.fa-user
span 欢迎来访者!
.item-content
p 👋🏻我是moh,一个
span(style="font-weight: bold; color: #3498db") 热爱编程
| 的技术爱好者,喜欢分享经验。😊
p ❓有问题欢迎提问,确保内容有意义,详情请见
a(href="https://how-to-ask.liushen.fun/" target="_blank" style="font-weight: bold; color: #2980b9") 提问的智慧
| 。如需联系我,欢迎通过
a(href="mailto:01@liushen.fun" style="font-weight: bold; color: #9b59b6") 邮箱
| 联系我!📧
#welcome-info
.error-message(style="height: 200px; display: flex; justify-content: center; align-items: center;")
p(style="text-align: center;")
span(style="font-size: 40px;") 😥
br
span(style="font-size: 16px;") 由于网络问题
br
span(style="font-size: 16px;") 位置API请求错误
br
span(style="font-size: 16px;") 请刷新重试呀🤗~

1.2、插入到侧边栏

结构实现了,下面将该结构插入到对应的位置,可以在当前目录下的index.pug找到对应结构,如下:

文件路径

1
[BlogRoot]\themes\butterfly\layout\includes\widget\index.pug

在代码中插入以下带号的那行代码,注意缩进问题
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
#aside-content.aside-content
//- post
if is_post()
- const tocStyle = page.toc_style_simple
- const tocStyleVal = tocStyle === true || tocStyle === false ? tocStyle : theme.toc.style_simple
if showToc && tocStyleVal
.sticky_layout
include ./card_post_toc.pug
else
!=partial('includes/widget/card_author', {}, {cache: true})
!=partial('includes/widget/card_poem', {}, {cache: true})
!=partial('includes/widget/card_rewards', {}, {cache: true})
!=partial('includes/widget/card_announcement', {}, {cache: true})
!=partial('includes/widget/card_top_self', {}, {cache: true})
.sticky_layout
if showToc
include ./card_post_toc.pug
if page.series
include ./card_post_series.pug
!=partial('includes/widget/card_recent_post', {}, {cache: true})
!=partial('includes/widget/card_ad', {}, {cache: true})
else
//- page
!=partial('includes/widget/card_author', {}, {cache: true})
+ !=partial('includes/widget/card_welcome', {}, {cache: true})
!=partial('includes/widget/card_poem', {}, {cache: true})
!=partial('includes/widget/card_rewards', {}, {cache: true})
!=partial('includes/widget/card_announcement', {}, {cache: true})
!=partial('includes/widget/card_top_self', {}, {cache: true})

.sticky_layout
if showToc
include ./card_post_toc.pug
!=partial('includes/widget/card_recent_post', {}, {cache: true})
!=partial('includes/widget/card_ad', {}, {cache: true})
!=partial('includes/widget/card_newest_comment', {}, {cache: true})
!=partial('includes/widget/card_categories', {}, {cache: true})
!=partial('includes/widget/card_tags', {}, {cache: true})
!=partial('includes/widget/card_archives', {}, {cache: true})
!=partial('includes/widget/card_webinfo', {}, {cache: true})
!=partial('includes/widget/card_bottom_self', {}, {cache: true})

二、添加样式美化

2.1、创建样式文件

创建欢迎卡片的样式文件:

1
[BlogRoot]\themes\butterfly\source\css\_layout\card-welcome.styl

添加以下样式代码:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
#aside-content
.card-widget.card-welcome
padding: 8px
.item-headline
margin: 12px 16px 0 16px
.item-content
margin: 0 16px 10px 16px
#welcome-info
text-align center
background-color: var(--liushen-card-bg)
border-radius: 12px
padding: 16px
margin: 8px
// border: 2px solid var(--liushen-text)
.ip-address
// 模糊效果
filter: blur(5px)
color: var(--default-bg-color)
transition: filter 0.5s
&:hover
filter: none

三、JavaScript逻辑实现

3.1 创建JavaScript文件

在静态资源目录创建JS文件:

1
[BlogRoot]/source/js/card-welcome.js

3.2 选择定位方案

碎碎念: 由于我觉得调用免费的获取ip地址的api经纬度不是很精确,因此我调用了付费的api 当前我也会提供免费的付费的js代码

方案一: 免费版(推荐新手尝试)

使用免费的IP-API服务,无需注册,但有速率限制。

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
// 显示欢迎信息
// 计算两点之间的距离(单位:公里)
function getDistance(lat1, lon1, lat2, lon2) {
const R = 6371;
const dLat = (lat2 - lat1) * Math.PI / 180;
const dLon = (lon2 - lon1) * Math.PI / 180;
const a = Math.sin(dLat / 2) * Math.sin(dLat / 2) +
Math.cos(lat1 * Math.PI / 180) * Math.cos(lat2 * Math.PI / 180) *
Math.sin(dLon / 2) * Math.sin(dLon / 2);
const c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a));
return Math.round(R * c);
}

// 获取IP位置信息
function fetchIpLocation() {
return fetch('http://ip-api.com/json/?fields=status,message,country,regionName,city,lat,lon,query&lang=zh-CN')
.then(response => response.json())
.then(data => {
if (data.status !== 'success') {
throw new Error(data.message || 'IP定位失败');
}
return {
ip: data.query,
data: {
country: data.country,
prov: data.regionName,
city: data.city,
district: '',
lng: data.lon,
lat: data.lat
}
};
})
.catch(error => {
console.error('获取IP位置信息失败:', error);
return null;
});
}
function showWelcome(ipLocation) {
if (!ipLocation || !ipLocation.data) {
console.error('ipLocation data is not available.');
return;
}

let dist = getDistance(24.4798, 118.0894, ipLocation.data.lat, ipLocation.data.lng);
let pos = ipLocation.data.country;
let ip = ipLocation.ip;
let posdesc;

// 以下的代码需要根据新API返回的结果进行相应的调整
switch (ipLocation.data.country) {
case "日本":
posdesc = "よろしく,一起去看樱花吗";
break;
case "美国":
posdesc = "Let us live in peace!";
break;
case "英国":
posdesc = "想同你一起夜乘伦敦眼";
break;
case "俄罗斯":
posdesc = "干了这瓶伏特加!";
break;
case "法国":
posdesc = "C'est La Vie";
break;
case "德国":
posdesc = "Die Zeit verging im Fluge.";
break;
case "澳大利亚":
posdesc = "一起去大堡礁吧!";
break;
case "加拿大":
posdesc = "拾起一片枫叶赠予你";
break;
case "中国":
pos = ipLocation.data.prov + " " + ipLocation.data.city + " " + ipLocation.data.district;
switch (ipLocation.data.prov) {
case "北京市":
posdesc = "北——京——欢迎你~~~";
break;
case "天津市":
posdesc = "讲段相声吧";
break;
case "河北省":
posdesc = "山势巍巍成壁垒,天下雄关铁马金戈由此向,无限江山";
break;
case "山西省":
posdesc = "展开坐具长三尺,已占山河五百余";
break;
case "内蒙古自治区":
posdesc = "天苍苍,野茫茫,风吹草低见牛羊";
break;
case "辽宁省":
posdesc = "我想吃烤鸡架!";
break;
case "吉林省":
posdesc = "状元阁就是东北烧烤之王";
break;
case "黑龙江省":
posdesc = "很喜欢哈尔滨大剧院";
break;
case "上海市":
posdesc = "众所周知,中国只有两个城市";
break;
case "江苏省":
switch (ipLocation.data.city) {
case "南京市":
posdesc = "这是我挺想去的城市啦";
break;
case "苏州市":
posdesc = "上有天堂,下有苏杭";
break;
default:
posdesc = "散装是必须要散装的";
break;
}
break;
case "浙江省":
switch (ipLocation.data.city) {
case "杭州市":
posdesc = "东风渐绿西湖柳,雁已还人未南归";
break;
default:
posdesc = "望海楼明照曙霞,护江堤白蹋晴沙";
break;
}
break;
case "河南省":
switch (ipLocation.data.city) {
case "郑州市":
posdesc = "豫州之域,天地之中";
break;
case "信阳市":
posdesc = "品信阳毛尖,悟人间芳华";
break;
case "南阳市":
posdesc = "臣本布衣,躬耕于南阳此南阳非彼南阳!";
break;
case "驻马店市":
posdesc = "峰峰有奇石,石石挟仙气嵖岈山的花很美哦!";
break;
case "开封市":
posdesc = "刚正不阿包青天";
break;
case "洛阳市":
posdesc = "洛阳牡丹甲天下";
break;
default:
posdesc = "可否带我品尝河南烩面啦?";
break;
}
break;
case "安徽省":
posdesc = "蚌埠住了,芜湖起飞";
break;
case "福建省":
posdesc = "井邑白云间,岩城远带山";
break;
case "江西省":
posdesc = "落霞与孤鹜齐飞,秋水共长天一色";
break;
case "山东省":
posdesc = "遥望齐州九点烟,一泓海水杯中泻";
break;
case "湖北省":
switch (ipLocation.data.city) {
case "黄冈市":
posdesc = "红安将军县!辈出将才!";
break;
case "武汉市":
posdesc = "你想去长江游泳嘛?";
break;
default:
posdesc = "来碗热干面~";
break;
}
break;
case "湖南省":
posdesc = "74751,长沙斯塔克";
break;
case "广东省":
switch (ipLocation.data.city) {
case "广州市":
posdesc = "看小蛮腰,喝早茶了嘛~";
break;
case "深圳市":
posdesc = "今天你逛商场了嘛~";
break;
case "阳江市":
posdesc = "阳春合水!博主家乡~ 欢迎来玩~";
break;
default:
posdesc = "来两斤福建人~";
break;
}
break;
case "广西壮族自治区":
posdesc = "桂林山水甲天下";
break;
case "海南省":
posdesc = "朝观日出逐白浪,夕看云起收霞光";
break;
case "四川省":
posdesc = "康康川妹子";
break;
case "贵州省":
posdesc = "茅台,学生,再塞200";
break;
case "云南省":
posdesc = "玉龙飞舞云缠绕,万仞冰川直耸天";
break;
case "西藏自治区":
posdesc = "躺在茫茫草原上,仰望蓝天";
break;
case "陕西省":
posdesc = "来份臊子面加馍";
break;
case "甘肃省":
posdesc = "羌笛何须怨杨柳,春风不度玉门关";
break;
case "青海省":
posdesc = "牛肉干和老酸奶都好好吃";
break;
case "宁夏回族自治区":
posdesc = "大漠孤烟直,长河落日圆";
break;
case "新疆维吾尔自治区":
posdesc = "驼铃古道丝绸路,胡马犹闻唐汉风";
break;
case "台湾省":
posdesc = "我在这头,大陆在那头";
break;
case "香港特别行政区":
posdesc = "永定贼有残留地鬼嚎,迎击光非岁玉";
break;
case "澳门特别行政区":
posdesc = "性感荷官,在线发牌";
break;
default:
posdesc = "带我去你的城市逛逛吧!";
break;
}
break;
default:
posdesc = "带我去你的国家逛逛吧";
break;
}

// 根据本地时间切换欢迎语
let timeChange;
let date = new Date();
if (date.getHours() >= 5 && date.getHours() < 11) timeChange = "<span>🌤️ 早上好,快趁机多睡点懒觉!</span>";
else if (date.getHours() >= 11 && date.getHours() < 13) timeChange = "<span>☀️ 中午好,记得午休喔~</span>";
else if (date.getHours() >= 13 && date.getHours() < 17) timeChange = "<span>🕞 下午好,饮茶先啦!</span>";
else if (date.getHours() >= 17 && date.getHours() < 19) timeChange = "<span>🚶‍♂️ 下班啦!主打一个不听老板话~</span>";
else if (date.getHours() >= 19 && date.getHours() < 24) timeChange = "<span>🌙 晚上好,来一起熬夜吧呜😭</span>";
else timeChange = "夜深了,早点休息,少熬夜";

let welcomeInfoElement = document.getElementById("welcome-info");

if (welcomeInfoElement) {
welcomeInfoElement.innerHTML =
`嗷嗷!热烈欢迎🤪!来自<br><b><span style="color: var(--default-bg-color)">${pos}</span></b><br> 的铁铁,你好呀!😝<br>${posdesc}🍂<br>你目前距博主约 <b><span style="color: var(--default-bg-color)">${dist}</span></b> 公里!<br>你的网络IP为:<b><span class="ip-address" style="font-size: 15px;">${ip}</span></b><br>${timeChange} <br>`;
} else {
console.log("Pjax无法获取元素");
}
}

// 判断是否存在 "welcome-info" 元素
function isWelcomeInfoAvailable() {
let welcomeInfoElement = document.getElementById("welcome-info");
return welcomeInfoElement !== null;
}

// Pjax 完成后调用的处理函数
function handlePjaxComplete(ipLocation) {
if (isWelcomeInfoAvailable()) {
showWelcome(ipLocation);
}
}

// 加载时调用
function onLoad() {
fetchIpLocation().then(ipLocation => {
if (isWelcomeInfoAvailable()) {
showWelcome(ipLocation);
}
document.addEventListener("pjax:complete", () => handlePjaxComplete(ipLocation));
});
}

// 绑定 window.onload 事件
window.onload = onLoad;

方案二 付费版(高精度定位)

我这里采用的是小小api,因为调用的api没有限制,但是有次数限制,所以请自行注册账号,并申请key 官网链接如下: https://api.nsuuu.com/

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
const longitude = 118.0894;
const Latitude = 24.4798;
const IP_LOCATION_API_KEY = GLOBAL_CONFIG.ipLocationApiKey || '';

function getDistance(e1, n1, e2, n2) {
const R = 6371;
const { sin, cos, asin, PI, hypot } = Math;
let getPoint = (e, n) => {
e *= PI / 180;
n *= PI / 180;
return { x: cos(n) * cos(e), y: cos(n) * sin(e), z: sin(n) };
};

let a = getPoint(e1, n1);
let b = getPoint(e2, n2);
let c = hypot(a.x - b.x, a.y - b.y, a.z - b.z);
let r = asin(c / 2) * 2 * R;
return Math.round(r);
}

function fetchUserIP() {
return fetch('https://v1.nsuuu.com/api/ua')
.then(response => response.json())
.then(data => {
if (data.code === 200 && data.data && data.data.ip) {
return data.data.ip;
} else {
throw new Error('获取IP失败');
}
})
.catch(error => {
console.error('获取用户IP失败:', error);
throw error;
});
}

function fetchIpLocation(ip) {
return fetch(`https://v1.nsuuu.com/api/ipip?ip=${ip}`, {
method: 'GET',
headers: {
'Authorization': `Bearer ${IP_LOCATION_API_KEY}`,
'Content-Type': 'application/json'
}
})
.then(response => response.json())
.then(data => {
if (data.code === 200 && data.data) {
return {
ip: data.data.ip,
data: {
country: data.data.country,
prov: data.data.province,
city: data.data.city,
district: '',
lng: parseFloat(data.data.longitude),
lat: parseFloat(data.data.latitude)
}
};
} else {
throw new Error(data.message || 'IP定位失败');
}
})
.catch(error => {
console.error('获取IP位置信息失败:', error);
throw error;
});
}

function fetchIpLocationWithCache() {
const cachedData = btf.saveToLocal.get('ipLocation');
if (cachedData) {
return Promise.resolve(cachedData);
}

return fetchUserIP()
.then(ip => fetchIpLocation(ip))
.then(ipLocation => {
btf.saveToLocal.set('ipLocation', ipLocation, 1);
return ipLocation;
});
}

function showWelcome(ipLocation) {
if (!ipLocation || !ipLocation.data) {
console.error('ipLocation data is not available.');
return;
}

let dist = getDistance(longitude, Latitude, ipLocation.data.lng, ipLocation.data.lat);
let pos = ipLocation.data.country;
let ip = ipLocation.ip;
let posdesc;

switch (ipLocation.data.country) {
case "日本":
posdesc = "よろしく,一起去看樱花吗";
break;
case "美国":
posdesc = "Let us live in peace!";
break;
case "英国":
posdesc = "想同你一起夜乘伦敦眼";
break;
case "俄罗斯":
posdesc = "Высушите эту бутылку водки!";
break;
case "法国":
posdesc = "C'est La Vie";
break;
case "德国":
posdesc = "Die Zeit verging im Fluge.";
break;
case "澳大利亚":
posdesc = "一起去大堡礁吧!";
break;
case "加拿大":
posdesc = "拾起一片枫叶赠予你";
break;
case "中国":
pos = ipLocation.data.prov + " " + ipLocation.data.city;
switch (ipLocation.data.prov) {
case "北京市":
posdesc = "北——京——欢迎你~~~";
break;
case "天津市":
posdesc = "讲段相声吧";
break;
case "河北省":
posdesc = "山势巍巍成壁垒,天下雄关铁马金戈由此向,无限江山";
break;
case "山西省":
posdesc = "展开坐具长三尺,已占山河五百余";
break;
case "内蒙古自治区":
posdesc = "天苍苍,野茫茫,风吹草低见牛羊";
break;
case "辽宁省":
posdesc = "我想吃烤鸡架!";
break;
case "吉林省":
posdesc = "状元阁就是东北烧烤之王";
break;
case "黑龙江省":
posdesc = "很喜欢哈尔滨大剧院";
break;
case "上海市":
posdesc = "众所周知,中国只有两个城市";
break;
case "江苏省":
switch (ipLocation.data.city) {
case "南京市":
posdesc = "这是我挺想去的城市啦";
break;
case "苏州市":
posdesc = "上有天堂,下有苏杭";
break;
case "无锡市":
posdesc = "无锡太美,无锡太美";
break;
default:
posdesc = "散装是必须要散装的";
break;
}
break;
case "浙江省":
posdesc = "东风渐绿西湖柳,雁已还人未南归";
break;
case "河南省":
switch (ipLocation.data.city) {
case "郑州市":
posdesc = "豫州之域,天地之中";
break;
case "南阳市":
posdesc = "臣本布衣,躬耕于南阳此南阳非彼南阳!";
break;
case "驻马店市":
posdesc = "峰峰有奇石,石石挟仙气嵖岈山的花很美哦!";
break;
case "开封市":
posdesc = "刚正不阿包青天";
break;
case "洛阳市":
posdesc = "洛阳牡丹甲天下";
break;
default:
posdesc = "可否带我品尝河南烩面啦?";
break;
}
break;
case "安徽省":
posdesc = "蚌埠住了,芜湖起飞";
break;
case "福建省":
posdesc = "井邑白云间,岩城远带山";
break;
case "江西省":
posdesc = "落霞与孤鹜齐飞,秋水共长天一色";
break;
case "山东省":
posdesc = "遥望齐州九点烟,一泓海水杯中泻";
break;
case "湖北省":
switch (ipLocation.data.city) {
case "黄冈市":
posdesc = "红安将军县!辈出将才!";
break;
default:
posdesc = "来碗热干面~";
break;
}
break;
case "湖南省":
switch (ipLocation.data.city) {
case "衡阳市":
posdesc = "老乡见老乡,两眼泪汪汪!";
break;
default:
posdesc = "74751,长沙斯塔克";
break;
}
break;
case "广东省":
switch (ipLocation.data.city) {
case "广州市":
posdesc = "看小蛮腰,喝早茶了嘛~";
break;
case "深圳市":
posdesc = "今天你996了嘛~";
break;
case "阳江市":
posdesc = "阳春合水!博主家乡~ 欢迎来玩~";
break;
default:
posdesc = "来两斤福建人~";
break;
}
break;
case "广西壮族自治区":
posdesc = "桂林山水甲天下";
break;
case "海南省":
posdesc = "朝观日出逐白浪,夕看云起收霞光";
break;
case "四川省":
posdesc = "康康川妹子";
break;
case "贵州省":
posdesc = "茅台,学生,再塞200";
break;
case "云南省":
posdesc = "玉龙飞舞云缠绕,万仞冰川直耸天";
break;
case "西藏自治区":
posdesc = "躺在茫茫草原上,仰望蓝天";
break;
case "陕西省":
posdesc = "来份臊子面加馍";
break;
case "甘肃省":
posdesc = "羌笛何须怨杨柳,春风不度玉门关";
break;
case "青海省":
posdesc = "牛肉干和老酸奶都好好吃";
break;
case "宁夏回族自治区":
posdesc = "大漠孤烟直,长河落日圆";
break;
case "新疆维吾尔自治区":
posdesc = "驼铃古道丝绸路,胡马犹闻唐汉风";
break;
case "台湾省":
posdesc = "我在这头,大陆在那头";
break;
case "香港特别行政区":
posdesc = "永定贼有残留地鬼嚎,迎击光非岁玉";
break;
case "澳门特别行政区":
posdesc = "性感荷官,在线发牌";
break;
default:
posdesc = "带我去你的城市逛逛吧!";
break;
}
break;
default:
posdesc = "带我去你的国家逛逛吧";
break;
}

let timeChange;
let date = new Date();
if (date.getHours() >= 5 && date.getHours() < 11) timeChange = "<span>🌤️ 早上好,快趁机多睡点懒觉!</span>";
else if (date.getHours() >= 11 && date.getHours() < 13) timeChange = "<span>☀️ 中午好,记得午休喔~</span>";
else if (date.getHours() >= 13 && date.getHours() < 17) timeChange = "<span>🕞 下午好,饮茶先啦!</span>";
else if (date.getHours() >= 17 && date.getHours() < 19) timeChange = "<span>🚶‍♂️ 下班啦!主打一个不听老板话~</span>";
else if (date.getHours() >= 19 && date.getHours() < 24) timeChange = "<span>🌙 晚上好,来一起熬夜吧呜😭</span>";
else timeChange = "夜深了,早点休息,少熬夜";

let welcomeInfoElement = document.getElementById("welcome-info");

if (welcomeInfoElement) {
welcomeInfoElement.innerHTML =
`嗷嗷!热烈欢迎🤪!来自<br><b><span style="color: var(--default-bg-color)">${pos}</span></b><br> 的铁铁,你好呀!😝<br>${posdesc}🍂<br>你目前距博主约 <b><span style="color: var(--default-bg-color)">${dist}</span></b> 公里!<br>你的网络IP为:<b><span class="ip-address" style="font-size: 15px;">${ip}</span></b><br>${timeChange} <br>`;
} else {
console.log("Pjax无法获取元素");
}
}

function isWelcomeInfoAvailable() {
let welcomeInfoElement = document.getElementById("welcome-info");
return welcomeInfoElement !== null;
}

function handlePjaxComplete() {
if (isWelcomeInfoAvailable()) {
fetchIpLocationWithCache().then(ipLocation => {
showWelcome(ipLocation);
}).catch(error => {
console.error('获取位置信息失败:', error);
});
}
}

function onLoad() {
if (isWelcomeInfoAvailable()) {
fetchIpLocationWithCache().then(ipLocation => {
showWelcome(ipLocation);
}).catch(error => {
console.error('获取位置信息失败:', error);
});
}
document.addEventListener("pjax:complete", handlePjaxComplete);
}

window.onload = onLoad;

4.2 需要在配置文件里面引入这个自定义的js

五、进阶配置 (付费版专用)

如果直接写key写到js里面,会造成严重的token值泄露,因此我将token写到自定义配置文件里面,js读取配置文件这样子就不会造成token值泄露

5.1、 配置环境变量

创建环境变量文件保护API密钥:

1
[blogRoot]/.env

添加你的API密钥

1
IP_LOCATION_API_KEY=你的密钥

5.2、加载环境变量脚本

创建Hexo脚本加载环境变量:

1
[blogRoot]/scripts/load-env.js

写入以下内容

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
const fs = require('fs');
const path = require('path');

hexo.on('generateBefore', function () {
const envPath = path.join(hexo.base_dir, '.env');

if (fs.existsSync(envPath)) {
const envContent = fs.readFileSync(envPath, 'utf-8');

envContent.split('\n').forEach(line => {
line = line.trim();

if (!line || line.startsWith('#')) return;

const match = line.match(/^([^=]+)=(.*)$/);
if (match) {
const key = match[1].trim();
let value = match[2].trim();

if ((value.startsWith('"') && value.endsWith('"')) ||
(value.startsWith("'") && value.endsWith("'"))) {
value = value.slice(1, -1);
}

process.env[key] = value;
}
});

hexo.log.info('✓ Environment variables loaded from .env file');
} else {
hexo.log.warn('.env file not found. Some features may not work properly.');
}
});


5.3、传递API密钥到前端

修改主题的配置文件:
[blogRoot]themes/butterfly/layout/_partial/config.pug

代码添加即➕号,内容注意格式缩进

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
 let highlightProvider = config.syntax_highlighter || (config.highlight.enable ? 'highlight.js' : config.prismjs.enable ? 'prismjs' : null)
const { copy, language, height_limit, fullpage, macStyle, shrink } = theme.code_blocks
let highlight = JSON.stringify({
plugin: highlightProvider,
highlightCopy: copy,
highlightLang: language,
highlightHeightLimit: height_limit,
highlightFullpage: fullpage,
highlightMacStyle: macStyle
})

+ let ipLocationApiKey = process.env.IP_LOCATION_API_KEY || ''

script.
const GLOBAL_CONFIG = {
root: '!{config.root}',
algolia: !{algolia},
localSearch: !{localSearch},
translate: !{translate},
highlight: !{highlight},
copy: {
success: '!{_p("copy.success")}',
error: '!{_p("copy.error")}',
noSupport: '!{_p("copy.noSupport")}'
},
relativeDate: {
homepage: !{theme.post_meta.page.date_format === 'relative'},
post: !{theme.post_meta.post.date_format === 'relative'}
},
runtime: '!{theme.aside.card_webinfo.runtime_date ? _p("aside.card_webinfo.runtime.unit") : ""}',
dateSuffix: {
just: '!{_p("date_suffix.just")}',
min: '!{_p("date_suffix.min")}',
hour: '!{_p("date_suffix.hour")}',
day: '!{_p("date_suffix.day")}',
month: '!{_p("date_suffix.month")}'
},
copyright: !{copyright},
lightbox: '!{ theme.lightbox || 'null' }',
Snackbar: !{Snackbar},
infinitegrid: {
js: '!{url_for(theme.asset.egjs_infinitegrid)}',
buttonText: '!{_p("load_more")}'
},
isPhotoFigcaption: !{theme.photofigcaption},
islazyloadPlugin: !{theme.lazyload.enable && !theme.lazyload.native},
isAnchor: !{theme.anchor.auto_update || false},
percent: {
toc: !{theme.toc.scroll_percent},
rightside: !{theme.rightside_scroll_percent},
},
autoDarkmode: !{theme.darkmode.enable && theme.darkmode.autoChangeMode === 1},
+ ipLocationApiKey: '!{ipLocationApiKey}'
}

5.4、在需要的js中引入即可格式如下

1
const IP_LOCATION_API_KEY = GLOBAL_CONFIG.ipLocationApiKey || '';

参考文章

background11