利用 SiteMap 随机访问站内页面

发布于 2025/08/12 建站手札 总字数:210 阅读时长:1 分钟

提供了一个很好的解决方案,通过使用 Hexo 的 sitemap 生成器和 JavaScript 代码来实现随机访问站内页面的功能 以下是你提供的步骤的详细解释:

AI摘要 QWEN

在网上查找博客美化过程时发现基本上都有“随便逛逛”的功能,于是自己也添加一个。 比较简单只有js代码,但是先要安装插件

前置条件

npm install hexo-generator-sitemap --save

在站点配置文件 _config.yaml中添加:

sitemap:
  path: 
    - sitemap.xml
    - sitemap.txt
  rel: false
  tags: true
  categories: true

添加js

在主题目录下添加·\themes\butterfly\source\js\random.js

function randomPost() {
    fetch('/sitemap.xml').then(res => res.text()).then(str => (new window.DOMParser()).parseFromString(str, "text/xml")).then(data => {
        let ls = data.querySelectorAll('url loc');
        let locationHref,locSplit;
        do {
            locationHref = ls[Math.floor(Math.random() * ls.length)].innerHTML
            locSplit = locationHref.split('/')[3] || ''
        } while (locSplit == '' || locSplit == 'tags');
        //若所有文章都如 https://…….com/posts/2022/07/…… 格式,主域名后字符是 posts,则循环条件改为:
        //while (locSplit !== 'posts');
        location.href = locationHref
    })
}

使用

使用,在菜单栏上添加

<a href="javascript:;" onclick="randomPost()" title="随机访问一篇文章">随机</a>

参考

木木木木木的博客 木木木木木 · immmmm.com

利用 SiteMap 随机访问站内页面

/posts/b5866b9e/
作者
biss
发布于
许可协议
CC BY-NC-SA 4.0
网站
订阅 打赏

Comments

利用 SiteMap 随机访问站内页面