Skip to main content

隨機按鈕

· One min read

之前在看 Wiwi 跟 Jaron 的 Blog 都有一顆隨機按鈕,今天就來實作一顆啦!我發現 Wiwi 是用 nginx 伺服器實現隨機跳轉的,但是我放在 Cloudflare Worker 上,自訂性沒那麼高。

接著我想到 SSG 理論上也能生成這個功能,於是詢問了 Gemini 就有了這個功能,程式碼如下:

import { useEffect } from "react";
import routes from "@generated/routes";
import Layout from "@theme/Layout";

export default function RandomBlogRedirect() {
useEffect(() => {
let blogPosts = routes
.filter((route) => route.path.startsWith("/blog/"))
.filter((route) => route.path.split("/").length === 3); // 只保留一级目录的博客文章
const randomPost = blogPosts[Math.floor(Math.random() * blogPosts.length)];
window.location.href = randomPost.path;
}, []);

return (
<Layout title="隨機跳轉中">
<p>🎲 正在搜尋文章,請稍候...</p>
</Layout>
);
}

這個直接當成一個頁面即可。