修改JavaScript随机重定向代码 实现URL轮询访问后自动重置
JavaScript随机重定向脚本修改方案
核心改动逻辑
- 移除原版本「Cookie存储单个固定索引、30天有效期内跳转同一地址」的逻辑
- Cookie改为存储未访问URL的索引数组,设置足够长的有效期避免循环中途记录丢失
- 每次访问优先读取Cookie中的剩余未访问索引池:如果Cookie为空则初始化全量索引池(包含所有URL的索引)
- 从剩余索引池中随机抽取1个索引作为本次跳转目标,抽取后将该索引从池中移除
- 如果移除后索引池为空,直接清空Cookie,下次访问自动重置全量池开启新一轮循环;如果池还有剩余地址,将更新后的池写回Cookie
- 保留原代码的
?debug调试模式逻辑不变
修改后完整代码
// URL跳转列表,可根据需求自行增删条目 var RedirectURLs = { "urls" : [ { "url" : "http://www.aftonbladet.se/" }, { "url" : "http://www.dn.se/" }, { "url" : "http://www.svd.se/" } ] } // 统计URL总数量 var totalUrlCount = RedirectURLs.urls.length; // 获取本次跳转的目标索引 var targetIndex = getNextTargetIndex(totalUrlCount); var gotoUrl = RedirectURLs.urls[targetIndex].url; // 调试模式逻辑:地址带?debug参数时仅展示跳转地址不实际跳转 if (window.location.search == "?debug") { document.write("Redirect URL: " + gotoUrl); } else { document.location = gotoUrl; } /** * 从剩余未访问池中抽取下一个跳转目标索引,同步更新Cookie记录 * @param {number} totalUrlCount 跳转列表总URL数 * @returns {number} 本次跳转的目标索引 */ function getNextTargetIndex(totalUrlCount) { let remainPool = []; const cookieValue = getCookie(); // 无历史记录时初始化全量索引池(数组0基索引) if (!cookieValue) { for (let i = 0; i < totalUrlCount; i++) { remainPool.push(i); } } else { // 解析Cookie中存储的剩余索引数组 remainPool = JSON.parse(cookieValue); } // 从剩余池中随机选取一个索引 const randomPosition = Math.floor(Math.random() * remainPool.length); const selectedIndex = remainPool[randomPosition]; // 从剩余池中移除已选中的索引 remainPool.splice(randomPosition, 1); // 更新Cookie记录 if (remainPool.length === 0) { // 所有URL都已访问,清空Cookie等待下一轮重置 clearCookie(); } else { // 存储更新后的剩余池,有效期设为365天 setCookie(JSON.stringify(remainPool), 365); } return selectedIndex; } /** * 写入Cookie * @param {string} value 要存储的内容 * @param {number} daysUntilExpire 有效天数 */ function setCookie(value, daysUntilExpire) { const expireDate = new Date(); expireDate.setTime(expireDate.getTime() + (daysUntilExpire * 24 * 60 * 60 * 1000)); // 加path=/保证整站可读取Cookie,编码处理特殊字符避免解析异常 document.cookie = `rnd=${encodeURIComponent(value)};expires=${expireDate.toUTCString()};path=/`; } /** * 读取Cookie中存储的未访问索引池 * @returns {string} 索引数组的JSON字符串,无记录时返回空字符串 */ function getCookie() { const cookieArr = document.cookie.split(';'); for(let i = 0; i < cookieArr.length; i++) { let cookieItem = cookieArr[i]; while (cookieItem.charAt(0) === ' ') cookieItem = cookieItem.substring(1); if (cookieItem.indexOf("rnd=") === 0) { return decodeURIComponent(cookieItem.substring(4, cookieItem.length)); } } return ""; } /** * 清空追踪用Cookie */ function clearCookie() { document.cookie = "rnd=;expires=Thu, 01 Jan 1970 00:00:00 UTC;path=/"; }
运行逻辑验证(以3个URL为例)
- 首次访问Cookie为空,初始化剩余索引池
[0,1,2],随机抽取1个索引跳转,剩余池移除该索引后写回Cookie - 第二次访问读取Cookie拿到剩余索引池,再次随机抽取未访问的索引跳转,更新剩余池
- 第三次访问时池中仅剩1个索引,直接跳转该地址,跳转后池为空清空Cookie
- 第四次访问检测到Cookie为空,重新初始化全量索引池,开启新一轮循环,完全匹配需求逻辑
内容的提问来源于stack exchange,提问作者Holy Geek
相关产品推荐
相关产品推荐

