// ==UserScript==
// @name 自动翻页
// @name:zh-CN 自动翻页
// @name:en Auto Pager — Load the Next Page When You Scroll to the Bottom
// @namespace https://github.com/yilecoding/helper-scripts
// @version 2025.09.11.12
// @description 论坛、搜索结果、文章列表滚到底自动加载下一页并拼接到当前页:自动识别「下一页」(rel=next、文字 / 图标按钮、分页条页码,不会把「下一篇」当成下一页)和内容区域,插入「第 N 页」分隔线并替换分页条;相对链接、懒加载图片自动修正,GBK 老论坛不乱码;防死循环、页数上限,加载失败可重试;内置 Discuz / Bing / 百度规则。菜单可按站点停用、手动加载下一页、停止,可选地址栏跟随当前页。
// @description:zh-CN 论坛、搜索结果、文章列表滚到底自动加载下一页并拼接到当前页:自动识别「下一页」(rel=next、文字 / 图标按钮、分页条页码,不会把「下一篇」当成下一页)和内容区域,插入「第 N 页」分隔线并替换分页条;相对链接、懒加载图片自动修正,GBK 老论坛不乱码;防死循环、页数上限,加载失败可重试;内置 Discuz / Bing / 百度规则。菜单可按站点停用、手动加载下一页、停止,可选地址栏跟随当前页。
// @description:en Automatically loads the next page of forums, search results and article lists when you scroll near the bottom and appends it to the current page: finds the next-page link (rel=next, text or icon buttons, pagination numbers — never a "next post" link) and the main content list, inserts a "Page N" divider and swaps in the new pagination bar; fixes relative links and lazy-loaded images, decodes GBK pages correctly; guards against loops with a page limit, and shows a retry button on errors. Built-in rules for Discuz, Bing and Baidu. Menu: disable per site, load next page now, stop, optionally keep the address bar on the page you are reading.
// @author 壹樂(V:ita1125)
// @match http://*/*
// @match https://*/*
// @noframes
// @grant GM_getValue
// @grant GM_setValue
// @grant GM_registerMenuCommand
// @grant GM_unregisterMenuCommand
// @license MIT
// @run-at document-idle
// @homepageURL https://github.com/yile2020/helper-scripts
// @supportURL https://github.com/yile2020/helper-scripts/issues
// @updateURL https://raw.githubusercontent.com/yile2020/helper-scripts/main/auto-pager/auto-pager.user.js
// @downloadURL https://raw.githubusercontent.com/yile2020/helper-scripts/main/auto-pager/auto-pager.user.js
// ==/UserScript==
// 脚本持续更新维护,欢迎 star / watch 仓库获取最新版本:
// https://github.com/yile2020/helper-scripts
(function () {
'use strict';
/** 日志前缀。控制台过滤框输入「自动翻页」只看本脚本。 */
const TAG = '[自动翻页]';
// =========================================================================
// 配置
// =========================================================================
const CONFIG = {
triggerScreens: 2, // 距页面底部不到这么多屏时加载下一页
minItems: 3, // 内容容器里同类子元素至少这么多个
minItemText: 8, // 同类子元素平均字数低于这个的是菜单 / 分页条,不是内容
itemTextCap: 300, // 单个子元素最多计这么多字,免得一个超长元素压过一整列
imageWeight: 40, // 一张图折合多少字(图片列表没什么文字)
maxPages: 30, // 最多拼到第几页(含当前页),防止无尽列表把内存吃光
};
const SEP_CLASS = 'auto-pager-sep';
const STATUS_CLASS = 'auto-pager-status';
/** 懒加载库把真实地址放在这些属性里(Discuz 用 file / zoomfile,知乎用 data-actualsrc)。 */
const LAZY_ATTRS = ['data-src', 'data-original', 'data-lazy-src', 'data-lazy', 'data-actualsrc', 'data-echo', 'data-url', 'file', 'zoomfile'];
// =========================================================================
// 站点规则
// =========================================================================
/**
* 通用识别搞不定或者不放心的站点,在这里写死选择器。字段都可选,没写的那一项照常走通用识别:
* name 日志里显示的名字
* host 匹配 location.hostname 的正则
* url 匹配 location.href 的正则
* when 页面上存在这个选择器才算命中(Discuz 这类开源程序部署在无数个域名上,只能按结构认)
* next 「下一页」链接的选择器(取第一个能用的)
* content 内容容器的选择器(当前页和下一页都按它找)
* pager 要跟着换成下一页的分页条(可以命中多个:顶部 + 底部)
* 第一条全部条件都满足的规则生效。
*/
const SITE_RULES = [
{
name: 'Discuz! 帖子列表',
when: '#threadlisttableid',
next: '.pg a.nxt',
content: '#threadlisttableid',
pager: '.pg',
},
{
name: 'Discuz! 帖子内容',
when: '#postlist > div[id^="post_"]',
next: '.pg a.nxt',
content: '#postlist',
pager: '.pg',
},
{
name: 'Bing 搜索',
host: /(?:^|\.)bing\.com$/,
url: /\/search\?/,
next: 'a.sb_pagN',
content: '#b_results',
pager: '#b_results > li.b_pag',
},
{
name: '百度搜索',
host: /(?:^|\.)baidu\.com$/,
url: /\/s\?/,
content: '#content_left',
pager: '#page',
},
];
function matchRule() {
return SITE_RULES.find((r) =>
(!r.host || r.host.test(location.hostname))
&& (!r.url || r.url.test(location.href))
&& (!r.when || document.querySelector(r.when))) || null;
}
// =========================================================================
// 存储(GM)
// =========================================================================
/**
* 启用/停用按站点(hostname)存:在某个站上关掉,不该影响别的站。
* 「地址栏跟随」是个人偏好,全局存。
*/
const Store = (() => {
const siteKey = 'site:' + location.hostname;
function site() {
return { disabled: false, ...GM_getValue(siteKey, {}) };
}
function saveSite(patch) {
GM_setValue(siteKey, { ...site(), ...patch });
}
function settings() {
return { syncUrl: false, ...GM_getValue('settings', {}) };
}
function saveSettings(patch) {
GM_setValue('settings', { ...settings(), ...patch });
}
return { site, saveSite, settings, saveSettings };
})();
// =========================================================================
// 找「下一页」
// =========================================================================
/**
* 输入一个文档(当前页,或 fetch 回来解析出的下一页)和它的 URL,返回 { url, how } 或 null。
* 顺序:rel=next → 文字 / aria-label / title → 分页条里当前页码的后一个。
* 每一步都要过同一套判据:同源 http(s)、不是指回本页、不是「下一篇」那种文章导航。
*/
const Finder = (() => {
/** 去掉两侧装饰后整段等于这些词才算(「下一页 >」「Next »」);「下一页的内容」不算。 */
const NEXT_WORD = /^(?:下一?页|下一?頁|后一?页|後一?頁|next(?:\s+page)?|older(?:\s+(?:posts?|entries|articles))?)$/i;
const DECOR = /^[\s«‹<←\[【((]+|[\s»›>→\]】))]+$/g;
/**
* 只有箭头的链接。Bootstrap 的「« ‹ 1 2 3 › »」里 › 是下一页、» 是尾页,
* 而 WordPress 等的「上一页 «」「» 下一页」里 » 又是下一页 —— 所以 › 分数高于 »,同时出现时取 ›。
*/
const ARROW_SCORE = { '›': 2, '>': 2, '»': 1, '>>': 1, '→': 1 };
/**
* 「下一篇 / 下一章」是文章之间的导航,自动拼接会把两篇不相干的文章接在一起。
* WordPress 的 next_post_link 还带着 rel="next",所以 rel=next 也要过这一关。
*/
const EXCLUDE = /下一?(?:篇|章|节|節|条|條|个|個|集|话|話|张|張|帖|主题|主題)|上一|前一|prev|previous|newer|next\s+(?:post|article|story|entry|chapter|episode|thread|topic|video)/i;
/** 文章导航的容器(WordPress 的 post-navigation、各主题的 nav-single / prev-next),里面的链接全不算。 */
const ARTICLE_NAV = /post-navigation|(?:post|entry|single|article)[_-]nav|nav[_-]single|prev[_-]next/i;
function textOf(el) {
return (el.textContent || '').replace(/\s+/g, ' ').trim();
}
/** 一段文字像不像「下一页」:0 不像,3 是文字,2/1 是箭头。 */
function wordScore(text) {
if (!text) return 0;
const core = text.replace(DECOR, '').trim();
if (core) return NEXT_WORD.test(core) ? 3 : 0;
return ARROW_SCORE[text.replace(/\s+/g, '')] || 0;
}
function classAndId(el) {
return (typeof el.className === 'string' ? el.className : '') + ' ' + (el.id || '');
}
function excluded(el) {
const labels = [textOf(el), el.getAttribute('aria-label') || '', el.getAttribute('title') || ''];
if (labels.some((s) => EXCLUDE.test(s))) return true;
// 分页条里「不可点」的下一页(最后一页上常见):自己或父级 disabled
for (let n = el, i = 0; n && n.nodeType === 1 && i < 6; n = n.parentElement, i++) {
const ci = classAndId(n);
if (ARTICLE_NAV.test(ci)) return true;
if (i < 2 && (/(?:^|\s)disabled(?:\s|$)/.test(ci) || n.getAttribute('aria-disabled') === 'true')) return true;
}
return false;
}
/** href → 可加载的绝对 URL(去掉 hash);不同源、非 http(s)、指回本页的返回 null。 */
function resolve(el, doc, pageUrl) {
const raw = el.getAttribute('href');
if (!raw) return null;
let u;
try {
u = new URL(raw, doc.baseURI || pageUrl);
} catch (e) {
return null;
}
if (u.protocol !== 'http:' && u.protocol !== 'https:') return null;
if (u.origin !== location.origin) return null;
u.hash = '';
const self = new URL(pageUrl);
self.hash = '';
if (u.href === self.href) return null;
return u.href;
}
function byRel(doc, pageUrl) {
for (const el of doc.querySelectorAll('link[rel~="next" i][href], a[rel~="next" i][href]')) {
if (el.tagName === 'A' && excluded(el)) continue;
const url = resolve(el, doc, pageUrl);
if (url) return { url, how: 'rel=next' };
}
return null;
}
function byText(doc, pageUrl) {
let best = null;
for (const a of doc.querySelectorAll('a[href]')) {
const score = Math.max(
wordScore(textOf(a)),
wordScore(a.getAttribute('aria-label') || ''),
wordScore(a.getAttribute('title') || ''),
);
if (!score || (best && score <= best.score)) continue;
if (excluded(a)) continue;
const url = resolve(a, doc, pageUrl);
if (url) best = { url, how: '文字匹配', score };
}
return best && { url: best.url, how: best.how };
}
const CURRENT_CLASS = /(?:^|\s)(?:current|active|cur|on|selected|thispage|now)(?:\s|$)/i;
const NUM = /^\d{1,5}$/;
/** 是不是「当前页码」:不是链接,或者自己 / 上两级带 aria-current、current/active 之类的类名。 */
function isCurrentMark(el) {
if (!el.closest('a[href]')) return true;
for (let n = el, i = 0; n && i < 3; n = n.parentElement, i++) {
if (n.getAttribute('aria-current') === 'page' || CURRENT_CLASS.test(classAndId(n))) return true;
}
return false;
}
/**
* 分页条只有页码没有「下一页」字样时:找到当前页码 N,在同一个分页条里找文字为 N+1 的链接。
* 「分页条」= 往上 4 级内第一个含 ≥2 个纯数字链接的祖先 —— 列表里的回复数、楼层号
* 也是不带链接的数字,靠这一条和真正的当前页码区分开。
*/
function byNumber(doc, pageUrl) {
for (const el of doc.body.querySelectorAll('*')) {
if (el.children.length || !NUM.test(textOf(el)) || !isCurrentMark(el)) continue;
let pager = null;
for (let n = el.parentElement, i = 0; n && n !== doc.body && i < 4; n = n.parentElement, i++) {
const nums = Array.from(n.querySelectorAll('a[href]')).filter((a) => NUM.test(textOf(a).replace(/^\.+\s*/, '')));
if (nums.length >= 2) {
pager = nums;
break;
}
}
if (!pager) continue;
const want = String(Number(textOf(el)) + 1);
const a = pager.find((x) => textOf(x).replace(/^\.+\s*/, '') === want && !excluded(x));
const url = a && resolve(a, doc, pageUrl);
if (url) return { url, how: '页码推断' };
}
return null;
}
function byRule(doc, pageUrl, rule) {
if (!rule || !rule.next) return null;
for (const el of doc.querySelectorAll(rule.next)) {
const url = resolve(el, doc, pageUrl);
if (url) return { url, how: '站点规则:' + rule.name };
}
return null;
}
function find(doc, pageUrl, rule) {
return byRule(doc, pageUrl, rule) || byRel(doc, pageUrl) || byText(doc, pageUrl) || byNumber(doc, pageUrl);
}
return { find };
})();
// =========================================================================
// 找「内容容器」
// =========================================================================
/**
* 内容容器 = 子元素里有一大组「同类」元素(同 tag + 同类名)、文字量最多的那个元素,
* 而且在下一页的同一位置也能找到它。只看当前页会被「当前页独有」的结构骗
* (置顶公告、本页才有的推荐位),所以要等下一页拿回来两边对照。
*/
const Content = (() => {
/** 这些区域里的列表是菜单、侧栏、页脚链接,不是内容。 */
const SKIP = 'nav, header, footer, aside, [role="navigation"], [role="banner"], [role="contentinfo"], [role="complementary"]';
/** 类名里带数字的去掉:WordPress 的 post-123、Discuz 的 normalthread_456 每项都不同。 */
function cleanClasses(el) {
return Array.from(el.classList).filter((c) => !/\d/.test(c) && c !== SEP_CLASS).sort();
}
function signature(el) {
return [el.tagName.toLowerCase()].concat(cleanClasses(el)).join('.');
}
/** 子元素里数量最多的同类组:{ sig, items }。 */
function dominantGroup(el) {
const groups = new Map();
for (const c of el.children) {
if (c.tagName === 'SCRIPT' || c.tagName === 'STYLE' || c.classList.contains(SEP_CLASS)) continue;
const sig = signature(c);
if (!groups.has(sig)) groups.set(sig, []);
groups.get(sig).push(c);
}
let best = null;
for (const [sig, items] of groups) if (!best || items.length > best.items.length) best = { sig, items };
return best;
}
function weight(el) {
const text = (el.textContent || '').replace(/\s+/g, '').length;
return Math.min(text + el.querySelectorAll('img').length * CONFIG.imageWeight, CONFIG.itemTextCap);
}
/** 定位路径:最近的稳定 id 起,往下逐级 tag + 类名;同一选择器命中多个时记下标。 */
function pathOf(el, doc) {
const parts = [];
let n = el;
for (; n && n !== doc.body && n !== doc.documentElement; n = n.parentElement) {
// 长串数字的 id 多半是每页不同的自增 id,不能拿来跨页定位
if (n.id && !/\d{3,}/.test(n.id)) {
parts.unshift('#' + CSS.escape(n.id));
break;
}
parts.unshift([n.tagName.toLowerCase()].concat(cleanClasses(n).map((c) => CSS.escape(c))).join('.'));
}
if (!n || n === doc.body) parts.unshift('body');
const selector = parts.join(' > ');
return { selector, index: Array.from(doc.querySelectorAll(selector)).indexOf(el) };
}
function locate(doc, path) {
return doc.querySelectorAll(path.selector)[path.index] || null;
}
function candidates(doc) {
const list = [];
for (const el of doc.body.querySelectorAll('*')) {
if (el.children.length < CONFIG.minItems || el.closest(SKIP)) continue;
const g = dominantGroup(el);
if (!g || g.items.length < CONFIG.minItems) continue;
const score = g.items.reduce((sum, c) => sum + weight(c), 0);
if (score / g.items.length < CONFIG.minItemText) continue;
// 当前页上不可见的(折叠的 tab、隐藏的模板)不算
if (doc === document && !el.getClientRects().length) continue;
list.push({ el, sig: g.sig, items: g.items, score });
}
return list.sort((a, b) => b.score - a.score);
}
/** 在当前页和下一页里都认得出的内容容器:{ el, path, sig } 或 null。 */
/** 规则写死了容器:只要两边都找得到就用它,不再打分。 */
function byRule(nextDoc, rule) {
const el = document.querySelector(rule.content);
if (!el || !nextDoc.querySelector(rule.content)) return null;
const g = dominantGroup(el);
if (!g) return null;
return { el, path: { selector: rule.content, index: 0 }, sig: g.sig, last: g.items[g.items.length - 1] };
}
function detect(nextDoc, rule) {
if (rule && rule.content) {
const hit = byRule(nextDoc, rule);
if (hit) return hit;
console.warn(TAG, `规则「${rule.name}」的内容选择器 ${rule.content} 没命中,改用通用识别`);
}
// 按日期分组的列表(每组一个标题 + 一串帖子)会选中外层:整组搬过来正好也是对的
for (const c of candidates(document)) {
const path = pathOf(c.el, document);
const there = locate(nextDoc, path);
if (!there || !Array.from(there.children).some((x) => signature(x) === c.sig)) continue;
return { el: c.el, path, sig: c.sig, last: c.items[c.items.length - 1] };
}
return null;
}
/** 下一页容器里要搬过来的子元素:第一个到最后一个同类元素之间的全部(表头、页内分页条不要)。 */
function itemsIn(doc, info) {
const box = locate(doc, info.path);
if (!box) return null;
const kids = Array.from(box.children);
const first = kids.findIndex((x) => signature(x) === info.sig);
if (first < 0) return [];
let last = first;
kids.forEach((x, i) => { if (signature(x) === info.sig) last = i; });
return kids.slice(first, last + 1).filter((x) => x.tagName !== 'SCRIPT' && x.tagName !== 'STYLE');
}
return { detect, itemsIn, pathOf };
})();
// =========================================================================
// 导入前的修正
// =========================================================================
/**
* 节点从下一页搬到当前页,相对地址会改按当前页解析:/blog/page/2/ 里的 ../../a.html
* 搬到 /blog/ 下就指到站外的 /a.html 去了。所以导入前按下一页的 全部转成绝对地址。
* 纯 #锚点 不动:内容已经在本页了,锚点指向它才对。
*/
const Fixer = (() => {
const URL_ATTRS = ['href', 'src', 'action', 'poster', 'data'];
const SKIP_SCHEME = /^\s*(?:#|javascript:|mailto:|tel:|data:|blob:|about:)/i;
function abs(raw, base) {
if (!raw || SKIP_SCHEME.test(raw)) return raw;
try {
return new URL(raw.trim(), base).href;
} catch (e) {
return raw;
}
}
function absSrcset(raw, base) {
if (!raw || /data:/i.test(raw)) return raw;
return raw.split(',').map((part) => {
const [u, ...desc] = part.trim().split(/\s+/);
return [abs(u, base)].concat(desc).join(' ');
}).join(', ');
}
/**
* 懒加载图片:页面上的懒加载脚本只盯着首屏时就在的
,后拼进来的永远停在占位图。
* 有真实地址就直接写进 src。
*/
function unlazy(img, base) {
const attr = LAZY_ATTRS.find((a) => img.getAttribute(a));
if (attr) {
const real = abs(img.getAttribute(attr), base);
if (img.getAttribute('src') !== real) img.setAttribute('src', real);
}
const set = img.getAttribute('data-srcset') || img.getAttribute('data-lazy-srcset');
if (set) img.setAttribute('srcset', absSrcset(set, base));
}
function fix(root, base) {
const els = [root].concat(Array.from(root.querySelectorAll('*')));
for (const el of els) {
for (const a of URL_ATTRS) if (el.hasAttribute(a)) el.setAttribute(a, abs(el.getAttribute(a), base));
if (el.hasAttribute('srcset')) el.setAttribute('srcset', absSrcset(el.getAttribute('srcset'), base));
if (el.tagName === 'IMG') unlazy(el, base);
// DOMParser 出来的