网页随机跳转功能通过javascript实现:基础版直接定义url数组并随机选取跳转;增强版支持fetch动态读取txt或json格式的外部链接列表,确保每次访问跳转至预设url中的任意一个。

实现网页随机跳转功能,即用户每次访问该页面时自动跳转到一组预设URL中的任意一个,无需手动选择或点击。
准备跳转链接列表
新建一个纯文本文件(如 redirect-list.txt),每行写一个目标网址,确保全部为完整URL(含 http:// 或 https://)。
这一步不能省略——缺少协议头的地址会导致跳转失败,浏览器会当作相对路径处理。
编写基础HTML跳转页
创建 index.html 文件,粘贴以下代码:
<script><br/>const urls = ["https://example.com", "https://google.com", "https://github.com"];<br/>const randomIndex = Math.floor(Math.random() * urls.length);<br/>window.location.href = urls[randomIndex];<br/></script>
注意:urls 数组必须与上一步准备的链接列表完全一致,顺序和数量都要核对。
增强版:从外部文件读取链接
方法一:使用 fetch 动态加载 redirect-list.txt
在 index.html 中替换 script 内容为:
<script><br/>fetch('redirect-list.txt')<br/> .then(r => r.text())<br/> .then(text => {<br/> const urls = text.split('\n').map(u => u.trim()).filter(u => u);<br/> if (urls.length === 0) throw new Error('链接列表为空');<br/> window.location.href = urls[Math.floor(Math.random() * urls.length)];<br/> });<br/></script>
方法二:用 JSON 格式管理更可靠
将 redirect-list.txt 改名为 redirect-list.json,内容改为:
[
"https://example.com",
"https://google.com",
"https://github.com"
]
对应 script 改为:
<script><br/>fetch('redirect-list.json')<br/> .then(r => r.json())<br/> .then(urls => {<br/> <strong>【urls 必须是数组,否则会报错】<br/> window.location.href = urls[Math.floor(Math.random() * urls.length)];<br/> });<br/></script>
部署并验证跳转行为
第一步:把 index.html 和链接列表文件(txt 或 json)一起上传到网站根目录或同一子目录下。
第二步:用浏览器直接访问 index.html 的完整 URL(如 https://yoursite.com/index.html)。
第三步:刷新页面多次,观察地址栏是否每次跳转到不同目标站——如果始终卡在某一个站,检查网络控制台是否有 404 报错,确认文件名和路径拼写完全正确。











