下述文件位置主要针对Butterfly主题,其他主题请自行修改!!!

教程

  1. 新建[BlogSource]/themes/butterfly/scripts/helpers/inject_elements.js文件:

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    hexo.extend.generator.register('random', function (locals) {
    const config = hexo.config.random || {}
    const posts = []
    for (const post of locals.posts.data) {
    if (post.random !== false) posts.push(post.path)
    }
    return {
    path: config.path || 'random/index.html',
    data: `<html><head><script>var posts=${JSON.stringify(posts)};window.open('/'+posts[Math.floor(Math.random() * posts.length)],"_self")</script></head></html>`
    }
    })
  2. 在你想要的位置引用/random/index.html即可

新版教程

  1. 新建themes/butterfly/scripts/helpers/inject_elements.js

    1
    2
    3
    4
    5
    6
    7
    8
    hexo.extend.filter.register('after_render:html', function (data) {
    const posts = []
    hexo.locals.get('posts').map(function (post) {
    if (post.random !== false) posts.push(post.path)
    })
    data += `<script>var posts=${JSON.stringify(posts)};function toRandomPost(){ window.pjax ? pjax.loadUrl('/'+posts[Math.floor(Math.random()*posts.length)]) : window.open('/'+posts[Math.floor(Math.random()*posts.length)], "_self"); };</script>`
    return data
    })
  2. 正常调用toRandomPost()函数即可。