说明

因为hexo可以很方便的在多个平台上免费部署,为了让自己的博客能uptime更久一段时间,很多老哥都和我一样,把自己的hexo博客在好多个平台上都部署了一份。

但是我一直想要一个功能,就是在别人访问的不是主站点的时候,提示他们,并让他们帮你查查主站是不是down了。这个功能即本文标题所述的“非主站提醒”

js脚本实现

其实实现起来并不复杂,一个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
35
36
37
38
39
40
41
document.addEventListener("DOMContentLoaded", function () {
// 直接定义允许的域名
const allowedDomain = "blog.musnow.top"; // 替换为你的主站域名
// 获取当前页面的域名
const currentDomain = window.location.hostname;

// 检查域名是否匹配
if (currentDomain !== allowedDomain) {
// 创建横幅提醒
const banner = document.createElement("div");
banner.id = "domainMismatchBanner";

// 动态生成链接
const link = document.createElement("a");
link.href = "https://" + allowedDomain; // 指向主站的链接
link.target = "_blank"; // 在新窗口或标签页中打开链接
link.style.color = "#b8dbff";
link.style.textDecoration = "underline";
link.innerText = "主站";

// 将链接添加到横幅内容中
banner.appendChild(document.createTextNode("您当前访问的是镜像站,如果"));
banner.appendChild(link);
banner.appendChild(document.createTextNode("无法访问,请联系站长,感谢!"));

// 将横幅应用CSS样式
banner.style.backgroundColor = "#fb7070";
banner.style.color = "#fff";
banner.style.textAlign = "center";
banner.style.padding = "3px";
banner.style.position = "fixed";
banner.style.bottom = "0"; // 将top改为bottom
banner.style.left = "0";
banner.style.width = "100%";
banner.style.zIndex = "1000";

// 将横幅添加到body
document.body.appendChild(banner);
}
});

把这个脚本复制,在hexo配置目录的source文件夹下创建一个js文件夹,将该脚本命名为domain_check.js并放入文件夹。

随后使用hexo-butterfly自带的head和bottom注入功能来引用这个脚本,建议在bottom里面引用。

1
2
3
4
5
6
7
8
9
# Inject
# Insert the code to head (before '</head>' tag) and the bottom (before '</body>' tag)
# 插入代码到头部 </head> 之前 和 底部 </body> 之前
inject:
head:
# - <script src="xxxx"></script>
bottom:
- <script src="/js/domain_check.js"></script> # 检查域名是否正确
# - <script src="xxxx"></script>

效果

效果如下,当访问主站的时候,不会有提示。当访问blog1这个镜像站的时候,就会有底部横幅提示。

image.png

image.png

手机上的效果也不差,对于一个提示来说足够了。

Screenshot_20231229_214855.jpg