// ==UserScript== // @name 小说阅读器 // @namespace https://tampermonkey.net/ // @version 7.10.3 // @description 从任意章节开始边读边下;找不到下一章时自动读目录;目录按章节号排序;可手动刷新完整目录;自动探测"查看完整目录"链接;净化文字(按字替换关键词);长按标题栏自定义标题识别格式;支持原网站模式;中间方块双击切换自动翻页;自动翻页时屏幕常亮;记住最近8本书;预加载下一章;多款护眼主题循环切换;目录支持勾选章节批量下载;支持云端备份/恢复;标点自动通配中英文 // @author You // @match *://*/* // @grant GM_xmlhttpRequest // @grant GM_registerMenuCommand // @grant GM_unregisterMenuCommand // @grant GM_setValue // @grant GM_getValue // @grant GM_notification // @connect * // @connect api.textdb.online // @connect textdb.online // @run-at document-idle // ==/UserScript== (function () { 'use strict'; // ==================== 配置 ==================== const CONFIG = { contentSelectors: [ '#content', '#chaptercontent', '#booktxt', '#chapter-content', '.content', '.chapter-content', '.reading-content', '.showtxt', '.txt', 'article', '#htmlContent', '.read-content' ], nextSelectors: [ '#next', '#next_url', '#pb_next', 'a[rel="next"]', '.next', '.next-chapter', '.chapter-next a', '.bottem2 a:last-child', '.page_chapter a:last-child', '#page_next', '.section-opt a:last-child' ], prevSelectors: [ '#prev', '#prev_url', '#pb_prev', 'a[rel="prev"]', '.prev', '.prev-chapter', '.chapter-prev a', '.bottem2 a:first-child', '.page_chapter a:first-child', '#page_prev', '.section-opt a:first-child' ], tocLinkSelectors: [ 'a[href*="list"]', 'a[href*="index"]', 'a[href*="directory"]', '.bookname a', '.book-name a', '#bookinfo a', '.bottem2 a:nth-child(2)', '.page_chapter a:nth-child(2)', '.section-opt a:nth-child(2)' ], tocListSelectors: [ '#list a', '#chapterlist a', '.listmain a', '#chapter-list a', '.chapter-list a', '#chapters a', '.chapters a', '.book-list a', '#booklist a', '.booklist a', '#list-chapterAll a' ], requestDelay: 800, maxChapters: 20000, tocMinCount: 1, }; const RECENT_KEY = 'ndr_recent_v2'; const PURIFY_KEY = 'ndr_purify_v1'; const TITLE_PATTERNS_KEY = 'ndr_title_patterns_v2'; const MAX_RECENT = 8; const NATIVE_KEY = 'ndr_native_active_v2'; const NATIVE_TIMEOUT = 30 * 60 * 1000; const NATIVE_BAR_AUTO_HIDE = 3000; const CLOUD_KEY_NAME = 'ndr_cloud_key_v1'; const CHAPTER_TITLE_RE = /^第\s*[\d一二三四五六七八九十百千万零两]+\s*[章节回]/; const END_MARKERS_RE = /(完本|本书完|已完结|全书完|全剧终|没有下一章|最后一章|这是最后一章|已看完)/; const BAD_BOOK_NAME_RE = /(小说|阅读|文学|书屋|书库|网|txt|最新章节|最新更新|全文阅读|免费阅读|在线阅读|无弹窗|无广告|首页|目录|书架|完本|完结|连载|正文|列表)/i; const SILENT_AUDIO_SRC = 'data:audio/wav;base64,UklGRiQAAABXQVZFZm10IBAAAAABAAEAQB8AAEAfAAABAAgAZGF0YQAAAAA='; const SCROLL_STEP_RATIO = 1.0; // 标点通配表:中英文标点互相兼容 const PUNC_MAP = { ',': '[,,]', ',': '[,,]', '。': '[。.]', '.': '[。.]', '(': '[((]', '(': '[((]', ')': '[))]', ')': '[))]', '、': '[、,,]', ':': '[::]', ':': '[::]', ';': '[;;]', ';': '[;;]', '!': '[!!]', '!': '[!!]', '?': '[??]', '?': '[??]', '“': '[“"「」]', '”': '[”"「」]', '‘': '[‘\']', '’': '[’\']', }; const DEFAULT_TITLE_PATTERNS = [ { example: '第1章', pattern: '^第\\s*\\d+\\s*[章节回]', enabled: true }, { example: '第一百章', pattern: '^第\\s*[零一二三四五六七八九十百千万两〇○]+\\s*[章节回]', enabled: true }, { example: '15【', pattern: '^\\d+\\s*[【\\[((]', enabled: true }, { example: '15.', pattern: '^\\d+\\s*[.。、]', enabled: true }, { example: '15 标题', pattern: '^\\d+\\s+\\S', enabled: false }, { example: '楔子', pattern: '^(楔子|序章|引子|前言|序言|开篇)', enabled: true }, { example: '【番外】', pattern: '^【?番外】?', enabled: true }, ]; // ==================== 工具 ==================== const sleep = ms => new Promise(r => setTimeout(r, ms)); const log = (...a) => console.log('[阅读器]', ...a); function escapeHtml(s) { return String(s).replace(/[&<>"']/g, c => ({ '&': '&', '<': '<', '>': '>', '"': '"', "'": ''' }[c])); } function escapeRegex(s) { return String(s).replace(/[.*+?^${}()|[\]\\]/g, '\\$&'); } function getSetting(k, d) { try { const v = GM_getValue('ndr_' + k); return v === undefined ? d : v; } catch (e) { return d; } } function setSetting(k, v) { try { GM_setValue('ndr_' + k, v); } catch (e) {} } function normalizeUrl(u) { try { const url = new URL(u); url.hash = ''; return url.href; } catch (e) { return u; } } function getHostOf(url) { try { return new URL(url).host || ''; } catch (e) { return ''; } } function genSessionId() { return Date.now().toString(36) + '_' + Math.random().toString(36).slice(2, 8); } function isBadHref(href) { if (!href) return true; if (href.startsWith('javascript:')) return true; if (href === '#' || href.endsWith('#')) return true; return false; } function filterBookName(name) { if (!name) return ''; const n = String(name).trim(); if (!n || n.length < 2 || n.length > 40) return ''; if (BAD_BOOK_NAME_RE.test(n)) return ''; return n; } function makeProgressLabel(s) { const ch = (s.title || '').trim(); if (ch) { let t = ch; if (t.length > 26) t = t.slice(0, 26) + '…'; return t; } if (Array.isArray(s.locator) && s.locator.length) { let t = String(s.locator[0] || '').trim(); if (t.length > 20) t = t.slice(0, 20) + '…'; if (t) return t; } return '(无进度)'; } function getBookKey(url) { if (!url) return ''; const bid = extractBookId(url); if (bid) return 'id:' + bid; const host = getHostOf(url); try { const u = new URL(url); const m = u.pathname.match(/^(\/(?:book|read|txt|novel|article|xiaoshuo)\/[^\/]+\/)/i); if (m) return 'toc:' + host + m[1]; const parts = u.pathname.split('/').filter(Boolean); if (parts.length >= 2) { parts.pop(); return 'toc:' + host + '/' + parts.join('/') + '/'; } } catch (e) {} return 'host:' + host; } // ==================== 标题识别格式 ==================== function loadTitlePatterns() { try { const raw = GM_getValue(TITLE_PATTERNS_KEY); if (!raw) return JSON.parse(JSON.stringify(DEFAULT_TITLE_PATTERNS)); const arr = typeof raw === 'string' ? JSON.parse(raw) : raw; if (!Array.isArray(arr) || !arr.length) return JSON.parse(JSON.stringify(DEFAULT_TITLE_PATTERNS)); return arr.filter(x => x && typeof x.pattern === 'string').map(x => ({ example: String(x.example || x.name || '未命名'), pattern: String(x.pattern), enabled: x.enabled !== false })); } catch (e) { return JSON.parse(JSON.stringify(DEFAULT_TITLE_PATTERNS)); } } function saveTitlePatterns(list) { try { GM_setValue(TITLE_PATTERNS_KEY, JSON.stringify(list)); } catch (e) {} } function loadActiveTitlePatterns() { return loadTitlePatterns().filter(p => p.enabled); } // 把例子翻译成正则:数字段通配、标点通配、其余转义 function exampleToPattern(example) { const s = String(example || '').trim(); if (!s) return ''; let result = ''; let i = 0; let matched = false; const CN_NUM = /[零一二三四五六七八九十百千万两〇○]/; while (i < s.length) { const ch = s[i]; // 阿拉伯数字段 → \d+ if (/\d/.test(ch)) { let j = i; while (j < s.length && /\d/.test(s[j])) j++; result += '\\d+'; i = j; matched = true; continue; } // 中文数字段 → 中文字符集+ if (CN_NUM.test(ch)) { let j = i; while (j < s.length && CN_NUM.test(s[j])) j++; result += '[零一二三四五六七八九十百千万两〇○]+'; i = j; matched = true; continue; } // 标点通配 if (PUNC_MAP[ch]) { result += PUNC_MAP[ch]; i++; matched = true; continue; } // 其它字符:转义 result += escapeRegex(ch); i++; } if (!matched) return '^' + escapeRegex(s); return '^' + result; } // ==================== 净化文字 ==================== function loadPurifyList() { try { const raw = GM_getValue(PURIFY_KEY); if (!raw) return []; const arr = typeof raw === 'string' ? JSON.parse(raw) : raw; return Array.isArray(arr) ? arr.filter(x => typeof x === 'string' && x) : []; } catch (e) { return []; } } function savePurifyList(list) { try { GM_setValue(PURIFY_KEY, JSON.stringify(list)); } catch (e) {} } function purifyText(text) { if (!text) return text; const list = loadPurifyList(); if (!list.length) return text; let result = text; for (const kw of list) { if (!kw) continue; result = result.split(kw).join(''); } return result; } function findNativeContentEl() { for (const sel of CONFIG.contentSelectors) { try { const el = document.querySelector(sel); if (el) { const t = (el.innerText || el.textContent || '').trim(); if (t.length > 50) return el; } } catch (e) {} } return null; } function applyPurifyToNativePage() { const list = loadPurifyList(); const container = findNativeContentEl(); if (!container) return; const walker = document.createTreeWalker(container, NodeFilter.SHOW_TEXT, null); const nodes = []; let n; while ((n = walker.nextNode())) { if (n.parentElement && n.parentElement.closest('#ndr-native-bar-host, #ndr-native-toc-host, #ndr-host')) continue; nodes.push(n); } nodes.forEach(node => { if (node.__ndrOrigText === undefined) node.__ndrOrigText = node.nodeValue; let text = node.__ndrOrigText; if (list.length) { for (const kw of list) { if (!kw) continue; text = text.split(kw).join(''); } } if (node.nodeValue !== text) node.nodeValue = text; }); } function restoreNativePageText() { const container = findNativeContentEl(); if (!container) return; const walker = document.createTreeWalker(container, NodeFilter.SHOW_TEXT, null); let n; while ((n = walker.nextNode())) { if (n.__ndrOrigText !== undefined) { n.nodeValue = n.__ndrOrigText; delete n.__ndrOrigText; } } } function reapplyPurifyToReader() { if (readerOpen && currentIndex >= 0) { const ch = store.chapters[currentIndex]; if (ch && ch.content) { const savedLocator = captureLocator(); renderChapter(currentIndex, false); if (savedLocator && savedLocator.length) { setTimeout(() => applyLocator(savedLocator), 60); } } } if (nativeMode.active) applyPurifyToNativePage(); } // ==================== Toast ==================== let toastEl = null; let toastTimer = null; function showToast(msg, duration) { if (!document.body) return; if (!toastEl) { toastEl = document.createElement('div'); toastEl.id = 'ndr-toast'; document.body.appendChild(toastEl); } toastEl.style.cssText = ` all: initial; position: fixed !important; top: 50% !important; left: 50% !important; transform: translate(-50%, -50%) !important; background: rgba(0,0,0,.86) !important; color: #fff !important; padding: 14px 24px !important; border-radius: 10px !important; font-size: 15px !important; font-family: -apple-system, BlinkMacSystemFont, "PingFang SC", sans-serif !important; z-index: 2147483647 !important; pointer-events: none !important; box-shadow: 0 4px 20px rgba(0,0,0,.3) !important; opacity: 0 !important; transition: opacity .22s !important; max-width: 80vw !important; text-align: center !important; line-height: 1.6 !important; display: block !important; white-space: pre-line !important; font-weight: 500 !important; letter-spacing: .3px !important; `; toastEl.textContent = msg; void toastEl.offsetWidth; toastEl.style.opacity = '1'; if (toastTimer) clearTimeout(toastTimer); toastTimer = setTimeout(() => { if (toastEl) toastEl.style.opacity = '0'; }, duration || 1700); } function toggleTapDirection() { settings.tapVertical = !settings.tapVertical; setSetting('tapVertical', settings.tapVertical); if (settings.tapVertical) { showToast('↕ 上下翻页模式\n点上半屏 = 上一页\n点下半屏 = 下一页'); } else { showToast('↔ 左右翻页模式\n点左半屏 = 上一页\n点右半屏 = 下一页'); } lastMenuKey = ''; updateMenu(); } // ==================== 章节号解析 ==================== function chineseToNumber(ch) { if (!ch) return 0; const map = { '零':0,'〇':0,'○':0,'一':1,'二':2,'两':2,'三':3,'四':4,'五':5,'六':6,'七':7,'八':8,'九':9,'十':10,'百':100,'千':1000,'万':10000,'亿':100000000 }; let hasWei = false; for (let w = 0; w < ch.length; w++) { if (map[ch[w]] >= 10) { hasWei = true; break; } } if (!hasWei) { let n = 0; for (let d = 0; d < ch.length; d++) { const dv = map[ch[d]]; if (dv === undefined || dv >= 10) continue; n = n * 10 + dv; } return n; } let num = 0, temp = 0; for (let i = 0; i < ch.length; i++) { const val = map[ch[i]]; if (val === undefined) continue; if (val >= 10) { if (temp === 0) temp = 1; num += temp * val; temp = 0; } else { temp = val; } } return num + temp; } function parseChapterNumber(title) { if (!title) return null; const s = String(title).replace(/[\s\u3000]+/g, ''); let m = s.match(/^(\d+)[【\[((]/); if (m) return parseInt(m[1], 10); m = s.match(/^(\d+)$/); if (m) return parseInt(m[1], 10); m = s.match(/第\s*(\d+)\s*[章节回]/); if (m) return parseInt(m[1], 10); m = s.match(/第\s*([零一二三四五六七八九十百千万两〇○]+)\s*[章节回]/); if (m) return chineseToNumber(m[1]); if (/^(楔子|序章|引子|前言|序言|开篇)/.test(s)) return 0; return null; } // ==================== 网络 ==================== function gmFetch(url) { let referer = location.href; try { referer = new URL(url).origin + '/'; } catch (e) {} return new Promise((resolve, reject) => { GM_xmlhttpRequest({ method: 'GET', url, responseType: 'arraybuffer', timeout: 30000, headers: { 'User-Agent': 'Mozilla/5.0 (Linux; Android 10; SM-G975F) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Mobile Safari/537.36', 'Referer': referer, 'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8', 'Accept-Language': 'zh-CN,zh;q=0.9', }, onload: res => { if (res.status >= 200 && res.status < 300) { try { resolve(decodeResponse(res)); } catch (e) { reject(e); } } else reject(new Error('HTTP ' + res.status)); }, onerror: () => reject(new Error('网络错误')), ontimeout: () => reject(new Error('请求超时')), }); }); } function decodeResponse(res) { const buffer = res.response; const headers = res.responseHeaders || ''; let charset = ''; const m = headers.match(/charset=([\w-]+)/i); if (m) charset = m[1].toLowerCase(); if (!charset) { const head = new Uint8Array(buffer.slice(0, 2048)); const probe = new TextDecoder('utf-8', { fatal: false }).decode(head); charset = probe.includes('\uFFFD') ? 'gbk' : 'utf-8'; } try { return new TextDecoder(charset).decode(buffer); } catch (e) { return new TextDecoder('utf-8').decode(buffer); } } function toDoc(html, baseUrl) { if (baseUrl) { const tag = ``; if (/]*>/i.test(html)) html = html.replace(/]*>/i, m => m + tag); else if (/]*>/i.test(html)) html = html.replace(/]*>/i, m => m + '' + tag + ''); else html = tag + html; } return new DOMParser().parseFromString(html, 'text/html'); } // ==================== 正文解析 ==================== function extractContent(doc) { let el = null; for (const sel of CONFIG.contentSelectors) { const e = doc.querySelector(sel); if (e) { const t = (e.innerText || e.textContent || '').trim(); if (t.length > 50) { el = e; break; } } } if (!el) el = doc.body; el.querySelectorAll( 'script,style,nav,header,footer,.ad,.ads,.advertisement,' + '.bottem,.bottem1,.bottem2,.readmiddle,.chapter-nav,.nav,.tips' ).forEach(n => n.remove()); let text = (el.innerText || el.textContent || '').trim(); return text.replace(/\n{3,}/g, '\n\n'); } function pageLooksEnded(doc, content) { const tail = (content || '').slice(-300); if (END_MARKERS_RE.test(tail)) return true; const bodyText = (doc.body && doc.body.innerText || '').slice(-500); if (END_MARKERS_RE.test(bodyText)) return true; return false; } function cleanTitleLine(line) { let title = String(line).replace(/\s+/g, ' ').trim(); title = title.replace(/[((]\s*第\s*\d+\s*\/\s*\d+\s*页\s*[))]/g, '').trim(); title = title.replace(/[((]\s*\d+\s*\/\s*\d+\s*页?\s*[))]/g, '').trim(); return title; } function matchTitlePattern(line, patterns) { for (const p of patterns) { try { if (new RegExp(p.pattern).test(line)) return cleanTitleLine(line); } catch (e) {} } return ''; } function pickTitleFromContent(content) { if (!content) return ''; const patterns = loadActiveTitlePatterns(); if (!patterns.length) return ''; const lines = content.split('\n').map(l => l.trim()).filter(Boolean); for (let i = 0; i < Math.min(lines.length, 8); i++) { const t = matchTitlePattern(lines[i], patterns); if (t && t.length >= 2 && t.length <= 100) return t; } return ''; } function extractTitle(doc, i, content) { const fromContent = pickTitleFromContent(content); if (fromContent) return fromContent; const sels = ['#chapter-title', '.chapter-title', '#title', '.title', 'h1', 'h2']; const patterns = loadActiveTitlePatterns(); for (const s of sels) { const el = doc.querySelector(s); if (el) { const t = (el.textContent || '').trim().replace(/\s+/g, ' '); if (!t || t.length > 100) continue; if (matchTitlePattern(t, patterns)) return cleanTitleLine(t); } } return ''; } function extractBookName(doc) { const title = (doc.title || '').trim(); let m = title.match(/[_\-||]([^_\-||]+)$/); if (m) { const n = filterBookName(m[1]); if (n && !/^第\s*\d/.test(n)) return n; } m = title.match(/^([^_\-||]+)[_\-||]/); if (m) { const n = filterBookName(m[1]); if (n && !/^第\s*\d/.test(n)) return n; } const meta = doc.querySelector('meta[property="og:novel:book_name"]'); if (meta && meta.content) { const n = filterBookName(meta.content); if (n) return n; } return ''; } function extractBookId(url) { try { const u = new URL(url); let m = u.pathname.match(/\/(?:book|read|txt|novel|article|xiaoshuo)\/([A-Za-z0-9_]+)\//i); if (m) return m[1]; const parts = u.pathname.split('/').filter(Boolean); if (parts.length >= 2) { const cand = parts[parts.length - 2]; if (/^\d+$/.test(cand)) return cand; } return ''; } catch (e) { return ''; } } // ==================== 找下一章/上一章 ==================== function findNextUrl(doc, currentUrl) { const cur = normalizeUrl(currentUrl); for (const sel of CONFIG.nextSelectors) { const a = doc.querySelector(sel); if (a && a.getAttribute('href') && !isBadHref(a.href)) { const u = normalizeUrl(a.href); if (u !== cur) return u; } } const links = Array.from(doc.querySelectorAll('a')); const pats = [/^下一[章页节篇]/, /^下章/, /^next\b/i, /下一[章页节篇]$/]; for (const a of links) { const t = (a.textContent || '').trim().replace(/\s+/g, ' '); if (!t || t.length > 12 || isBadHref(a.href)) continue; if (pats.some(p => p.test(t))) { const u = normalizeUrl(a.href); if (u !== cur) return u; } } for (const a of links) { const t = (a.textContent || '').trim(); if (isBadHref(a.href)) continue; if (/下一[章页节]/.test(t) && t.length <= 20) { const u = normalizeUrl(a.href); if (u !== cur) return u; } } return null; } function findPrevUrl(doc, currentUrl) { const cur = normalizeUrl(currentUrl); for (const sel of CONFIG.prevSelectors) { const a = doc.querySelector(sel); if (a && a.getAttribute('href') && !isBadHref(a.href)) { const u = normalizeUrl(a.href); if (u !== cur) return u; } } const links = Array.from(doc.querySelectorAll('a')); const pats = [/^上一[章页节篇]/, /^上章/, /^prev\b/i, /上一[章页节篇]$/]; for (const a of links) { const t = (a.textContent || '').trim().replace(/\s+/g, ' '); if (!t || t.length > 12 || isBadHref(a.href)) continue; if (pats.some(p => p.test(t))) { const u = normalizeUrl(a.href); if (u !== cur) return u; } } for (const a of links) { const t = (a.textContent || '').trim(); if (isBadHref(a.href)) continue; if (/上一[章页节]/.test(t) && t.length <= 20) { const u = normalizeUrl(a.href); if (u !== cur) return u; } } return null; } // ==================== 目录 ==================== function findTOCUrl(doc, currentUrl) { for (const sel of CONFIG.tocLinkSelectors) { const a = doc.querySelector(sel); if (a && a.href && !isBadHref(a.href)) { const u = normalizeUrl(a.href); if (u !== normalizeUrl(currentUrl)) return u; } } const links = Array.from(doc.querySelectorAll('a')); for (const a of links) { const t = (a.textContent || '').trim(); if (/^(目录|返回目录|章节目录|书籍目录|目 录|目錄|回目录)$/.test(t)) { if (a.href && !isBadHref(a.href)) { const u = normalizeUrl(a.href); if (u !== normalizeUrl(currentUrl)) return u; } } } try { const u = new URL(currentUrl); const m = u.pathname.match(/^(\/(?:book|read|txt|novel|article|xiaoshuo)\/[^\/]+\/)/i); if (m) return u.origin + m[1]; const parts = u.pathname.split('/').filter(Boolean); if (parts.length >= 2) { parts.pop(); return u.origin + '/' + parts.join('/') + '/'; } } catch (e) {} return null; } function parseTOCList(doc) { const results = []; const seen = new Set(); for (const sel of CONFIG.tocListSelectors) { const as = doc.querySelectorAll(sel); if (as.length >= CONFIG.tocMinCount) { as.forEach(a => { if (!a.href || isBadHref(a.href)) return; const title = (a.textContent || '').trim(); if (!title || title.length > 100) return; const u = normalizeUrl(a.href); if (seen.has(u)) return; seen.add(u); results.push({ title, url: u }); }); if (results.length >= CONFIG.tocMinCount) return results; results.length = 0; seen.clear(); } } const all = Array.from(doc.querySelectorAll('a')); for (const a of all) { if (!a.href || isBadHref(a.href)) continue; const title = (a.textContent || '').trim(); if (!title || title.length > 80) continue; if (!CHAPTER_TITLE_RE.test(title)) continue; const u = normalizeUrl(a.href); if (seen.has(u)) continue; seen.add(u); results.push({ title, url: u }); } return results; } function findFullTOCLink(doc) { const links = Array.from(doc.querySelectorAll('a')); for (const a of links) { if (!a.href || isBadHref(a.href)) continue; const t = (a.textContent || '').trim(); if (/^(查看完整目录|完整目录|全部章节|查看全部章节|完整章节|全部目录|查看全部|全部)$/.test(t)) { return normalizeUrl(a.href); } } return null; } async function fetchTOCList(tocUrl) { const html = await gmFetch(tocUrl); const doc = toDoc(html, tocUrl); let list = parseTOCList(doc); if (list.length < 30) { const fullLink = findFullTOCLink(doc); if (fullLink && normalizeUrl(fullLink) !== normalizeUrl(tocUrl)) { try { log('[目录] 章节偏少(' + list.length + '),尝试完整目录:' + fullLink); const html2 = await gmFetch(fullLink); const doc2 = toDoc(html2, fullLink); const list2 = parseTOCList(doc2); if (list2.length > list.length) { log('[目录] 完整目录已抓取:' + list2.length + ' 章'); return list2; } } catch (e) { log('[目录] 完整目录抓取失败:' + e.message); } } } return list; } function parseUrlStructure(url) { try { const u = new URL(url); const m = u.pathname.match(/^(.*\/)(\d+)(?:_(\d+))?(\.\w+)?$/); if (!m) return null; return { origin: u.origin, dir: m[1], stem: m[2], page: m[3] ? parseInt(m[3], 10) : 1, ext: m[4] || '', hasPageSuffix: !!m[3], }; } catch (e) { return null; } } function findNextFromTOC(tocList, currentUrl) { const cur = normalizeUrl(currentUrl); let idx = tocList.findIndex(item => normalizeUrl(item.url) === cur); if (idx >= 0) { if (idx + 1 < tocList.length) return tocList[idx + 1].url; return null; } const st = parseUrlStructure(currentUrl); if (st) { const curNum = parseInt(st.stem, 10); let best = null, bestNum = Infinity; for (const item of tocList) { const s2 = parseUrlStructure(item.url); if (!s2) continue; const n = parseInt(s2.stem, 10); if (n > curNum && n < bestNum) { bestNum = n; best = item.url; } } if (best) return best; } return null; } function findPrevFromTOC(tocList, currentUrl) { const cur = normalizeUrl(currentUrl); let idx = tocList.findIndex(item => normalizeUrl(item.url) === cur); if (idx > 0) return tocList[idx - 1].url; const st = parseUrlStructure(currentUrl); if (st) { const curNum = parseInt(st.stem, 10); let best = null, bestNum = -1; for (const item of tocList) { const s2 = parseUrlStructure(item.url); if (!s2) continue; const n = parseInt(s2.stem, 10); if (n < curNum && n > bestNum) { bestNum = n; best = item.url; } } if (best) return best; } return null; } function guessNextUrls(currentUrl) { const st = parseUrlStructure(currentUrl); if (!st) return []; const candidates = []; candidates.push(`${st.origin}${st.dir}${st.stem}_${st.page + 1}${st.ext}`); const nxt = (parseInt(st.stem, 10) + 1).toString(); candidates.push(`${st.origin}${st.dir}${nxt.padStart(st.stem.length, '0')}${st.ext}`); candidates.push(`${st.origin}${st.dir}${nxt}${st.ext}`); return Array.from(new Set(candidates)); } // ==================== 综合找下一章 ==================== async function resolveNextUrl(doc, currentUrl, currentContent) { const cur = normalizeUrl(currentUrl); const fromDom = findNextUrl(doc, currentUrl); if (fromDom) { log('[下一章] 页面按钮命中'); return { url: fromDom }; } if (pageLooksEnded(doc, currentContent)) { log('[下一章] 页面提示已完结'); return { ended: true }; } if (store.tocList && store.tocList.length) { const next = findNextFromTOC(store.tocList, currentUrl); if (next) { log('[下一章] 缓存目录命中'); return { url: next }; } log('[下一章] 目录中已到末尾'); return { ended: true }; } if (!store.tocList || store.tocList.length === 0) { let tocUrl = store.tocUrl; if (!tocUrl) { tocUrl = findTOCUrl(doc, currentUrl); if (tocUrl) store.tocUrl = tocUrl; } if (tocUrl) { try { const list = await fetchTOCList(tocUrl); if (list && list.length >= CONFIG.tocMinCount) { store.tocList = list; updateMenu(); const next = findNextFromTOC(store.tocList, currentUrl); if (next) return { url: next }; return { ended: true }; } } catch (e) {} } } const guessed = guessNextUrls(currentUrl); for (const u of guessed) { if (normalizeUrl(u) === cur) continue; try { const html = await gmFetch(u); const d = toDoc(html, u); const c = extractContent(d); if (c && c.length >= 50 && c.slice(0, 100) !== (currentContent || '').slice(0, 100)) { return { url: u }; } } catch (e) {} await sleep(150); } return null; } async function resolvePrevUrl(doc, currentUrl) { const fromDom = findPrevUrl(doc, currentUrl); if (fromDom) return fromDom; if (store.tocList && store.tocList.length) { const prev = findPrevFromTOC(store.tocList, currentUrl); if (prev) return prev; } if (!store.tocList || store.tocList.length === 0) { let tocUrl = store.tocUrl; if (!tocUrl) { tocUrl = findTOCUrl(doc, currentUrl); if (tocUrl) store.tocUrl = tocUrl; } if (tocUrl) { try { const list = await fetchTOCList(tocUrl); if (list && list.length >= CONFIG.tocMinCount) { store.tocList = list; updateMenu(); const prev = findPrevFromTOC(store.tocList, currentUrl); if (prev) return prev; } } catch (e) {} } } return null; } // ==================== 状态 ==================== const store = { bookName: '', bookId: '', tocUrl: '', tocList: [], chapters: [], fetching: false, finished: false, stopped: false, }; const settings = { fontSize: getSetting('fontSize', 18) || 18, lineHeight: getSetting('lineHeight', 1.9) || 1.9, theme: getSetting('theme', 'light') || 'light', mode: getSetting('mode', 'page') || 'page', tapVertical: getSetting('tapVertical', false) ? true : false, autoPageEnabled: getSetting('autoPageEnabled', false) ? true : false, autoPageInterval: getSetting('autoPageInterval', 10) || 10, }; // ==================== Session ==================== let currentSessionId = null; function loadRecentSessions() { try { const raw = GM_getValue(RECENT_KEY); if (!raw) return []; const arr = typeof raw === 'string' ? JSON.parse(raw) : raw; if (!Array.isArray(arr)) return []; return arr.filter(s => s && s.url).map(s => { if (!s.id) s.id = genSessionId(); if (!s.host && s.url) s.host = getHostOf(s.url); return s; }); } catch (e) { return []; } } function saveRecentSessions(list) { try { const trimmed = list.slice(0, MAX_RECENT); GM_setValue(RECENT_KEY, JSON.stringify(trimmed)); } catch (e) {} } function upsertRecentSession(entry) { try { if (!entry || !entry.id) return; const list = loadRecentSessions(); const idx = list.findIndex(s => s.id === entry.id); if (idx >= 0) list[idx] = entry; else list.unshift(entry); list.sort((a, b) => (b.time || 0) - (a.time || 0)); saveRecentSessions(list); } catch (e) {} } function loadSession() { const list = loadRecentSessions(); return list[0] || null; } function saveSessionNow() { if (currentIndex < 0) return; if (!currentSessionId) return; const ch = store.chapters[currentIndex]; if (!ch) return; const locator = captureLocator(); const pageUrl = ch.url || location.href; const bookName = (store.bookName || '').trim() || extractBookName(document) || ''; const bookId = (store.bookId || '').trim() || extractBookId(pageUrl) || ''; const entry = { id: currentSessionId, url: pageUrl, bookName: bookName, bookId: bookId, host: getHostOf(pageUrl), title: ch.title || '', locator: locator, time: Date.now(), }; upsertRecentSession(entry); } let saveTimer = null; function scheduleSave() { if (!readerOpen) return; if (saveTimer) return; saveTimer = setTimeout(() => { saveTimer = null; saveSessionNow(); }, 500); } // ==================== 屏幕常亮 ==================== let wakeLock = null; let wakeLockWanted = false; let silentAudio = null; async function requestWakeLock() { wakeLockWanted = true; if (!('wakeLock' in navigator)) { log('[常亮] 本浏览器不支持 Wake Lock,仅用静音音频'); return; } try { if (wakeLock) return; wakeLock = await navigator.wakeLock.request('screen'); wakeLock.addEventListener('release', () => { wakeLock = null; if (wakeLockWanted && document.visibilityState === 'visible') { setTimeout(requestWakeLock, 300); } }); log('[常亮] Wake Lock 已激活'); } catch (e) { log('[常亮] Wake Lock 申请失败:' + e.message); } } async function releaseWakeLock() { wakeLockWanted = false; if (wakeLock) { try { await wakeLock.release(); } catch (e) {} wakeLock = null; log('[常亮] Wake Lock 已释放'); } } function startSilentAudio() { try { if (!silentAudio) { silentAudio = new Audio(SILENT_AUDIO_SRC); silentAudio.loop = true; silentAudio.volume = 0; silentAudio.setAttribute('playsinline', ''); silentAudio.setAttribute('webkit-playsinline', ''); } const p = silentAudio.play(); if (p && p.catch) { p.then(() => log('[静音] 已启动')) .catch(e => log('[静音] 播放失败:' + e.message)); } } catch (e) { log('[静音] 异常:' + e.message); } } function stopSilentAudio() { if (silentAudio) { try { silentAudio.pause(); silentAudio.currentTime = 0; } catch (e) {} log('[静音] 已停止'); } } document.addEventListener('visibilitychange', () => { if (document.visibilityState === 'visible' && wakeLockWanted && !wakeLock) { requestWakeLock(); } }); // ==================== 自动翻页 ==================== let autoPageTimer = null; let autoPaging = false; let boxClickTimer = null; let lastReaderBoxTap = 0; function startAutoPage() { settings.autoPageEnabled = true; setSetting('autoPageEnabled', true); startAutoPageTimer(); requestWakeLock(); startSilentAudio(); } function stopAutoPage() { settings.autoPageEnabled = false; setSetting('autoPageEnabled', false); if (autoPageTimer) { clearTimeout(autoPageTimer); autoPageTimer = null; } releaseWakeLock(); stopSilentAudio(); } function startAutoPageTimer() { if (!settings.autoPageEnabled) return; if (!readerOpen && !nativeMode.active) return; if (autoPageTimer) clearTimeout(autoPageTimer); const ms = Math.max(2000, settings.autoPageInterval * 1000); autoPageTimer = setTimeout(() => { autoPageTimer = null; if (!settings.autoPageEnabled) return; if (readerOpen) { autoPaging = true; try { tapNext(); } finally { autoPaging = false; } if (autoPageTimer === null && settings.autoPageEnabled) startAutoPageTimer(); } else if (nativeMode.active) { autoPaging = true; try { nativeScrollBy(1); } finally { autoPaging = false; } if (autoPageTimer === null && settings.autoPageEnabled && nativeMode.active) startAutoPageTimer(); } }, ms); } function resetAutoPageTimer() { if (!settings.autoPageEnabled) return; if (autoPaging) return; startAutoPageTimer(); } function toggleAutoPage() { if (!readerOpen && !nativeMode.active) { alert('请先在脚本阅读器或原网站模式里打开一本书。'); return; } if (settings.autoPageEnabled) { stopAutoPage(); showToast('⏹ 自动翻页已关闭'); } else { const input = prompt('自动翻页间隔(秒):', String(settings.autoPageInterval || 10)); if (input === null) return; const sec = parseInt(input, 10); if (!sec || sec < 2 || sec > 600) { alert('请输入 2 到 600 之间的秒数'); return; } settings.autoPageInterval = sec; setSetting('autoPageInterval', sec); startAutoPage(); showToast('▶ 自动翻页已开启\n每 ' + sec + ' 秒翻一页\n屏幕保持常亮'); } lastMenuKey = ''; updateMenu(); } // ==================== 原网站模式 ==================== const NATIVE_STYLE_ID = 'ndr-native-style'; const nativeMode = { active: false, barHost: null, tocHost: null, goPrev: null, goNext: null }; function saveNativeFlag() { try { GM_setValue(NATIVE_KEY, JSON.stringify({ t: Date.now() })); } catch (e) {} } function refreshNativeFlag() { saveNativeFlag(); } function isNativeSaved() { try { const raw = GM_getValue(NATIVE_KEY); if (!raw) return false; const data = typeof raw === 'string' ? JSON.parse(raw) : raw; if (!data || !data.t) return false; if (Date.now() - data.t > NATIVE_TIMEOUT) { GM_setValue(NATIVE_KEY, ''); return false; } return true; } catch (e) { return false; } } function clearNativeFlag() { try { GM_setValue(NATIVE_KEY, ''); } catch (e) {} } function applyNativeStyle() { let style = document.getElementById(NATIVE_STYLE_ID); if (!style) { style = document.createElement('style'); style.id = NATIVE_STYLE_ID; document.head.appendChild(style); } const fs = settings.fontSize; const lh = settings.lineHeight; const theme = settings.theme; const EXCLUDE = ':not(#ndr-native-bar-host):not(#ndr-native-toc-host)'; let css = ` html, body { font-size: ${fs}px !important; } body p${EXCLUDE}, body article${EXCLUDE}, body section${EXCLUDE}, body li${EXCLUDE}, body div${EXCLUDE}, body span${EXCLUDE}, body a${EXCLUDE}, body td${EXCLUDE}, body th${EXCLUDE}, body strong${EXCLUDE}, body em${EXCLUDE}, body b${EXCLUDE}, body i${EXCLUDE}, body h1${EXCLUDE}, body h2${EXCLUDE}, body h3${EXCLUDE}, body h4${EXCLUDE}, body h5${EXCLUDE}, body h6${EXCLUDE} { font-size: ${fs}px !important; line-height: ${lh} !important; } `; if (theme === 'sepia') { css += ` html${EXCLUDE}, body${EXCLUDE} { background-color: #f4ecd8 !important; color: #5b4636 !important; } body *${EXCLUDE} { background-color: transparent !important; color: #5b4636 !important; border-color: #e0d5bd !important; } body a${EXCLUDE} { color: #8a6d3b !important; } `; } else if (theme === 'dark') { css += ` html${EXCLUDE}, body${EXCLUDE} { background-color: #16171a !important; color: #c9ccd1 !important; } body *${EXCLUDE} { background-color: transparent !important; color: #c9ccd1 !important; border-color: #2a2c31 !important; } body a${EXCLUDE} { color: #7aa7f0 !important; } body img${EXCLUDE} { opacity: 0.85 !important; } body input${EXCLUDE}, body textarea${EXCLUDE} { background-color: #1e2024 !important; color: #c9ccd1 !important; } `; } else if (theme === 'green') { css += ` html${EXCLUDE}, body${EXCLUDE} { background-color: #C7EDCC !important; color: #2C3E2E !important; } body *${EXCLUDE} { background-color: transparent !important; color: #2C3E2E !important; border-color: #AECBB3 !important; } body a${EXCLUDE} { color: #2E5A3E !important; } `; } else if (theme === 'wood') { css += ` html${EXCLUDE}, body${EXCLUDE} { background-color: #F5EFE6 !important; color: #3E3A39 !important; } body *${EXCLUDE} { background-color: transparent !important; color: #3E3A39 !important; border-color: #E3D6C8 !important; } body a${EXCLUDE} { color: #8C6D4F !important; } `; } else if (theme === 'blue') { css += ` html${EXCLUDE}, body${EXCLUDE} { background-color: #D9E4F5 !important; color: #1F2D3D !important; } body *${EXCLUDE} { background-color: transparent !important; color: #1F2D3D !important; border-color: #C0CEE3 !important; } body a${EXCLUDE} { color: #2B6B9C !important; } `; } else if (theme === 'paper') { css += ` html${EXCLUDE}, body${EXCLUDE} { background-color: #FAFAFA !important; color: #333333 !important; } body *${EXCLUDE} { background-color: transparent !important; color: #333333 !important; border-color: #E0E0E0 !important; } body a${EXCLUDE} { color: #4A90E2 !important; } `; } style.textContent = css; } function removeNativeStyle() { const style = document.getElementById(NATIVE_STYLE_ID); if (style) try { style.remove(); } catch (e) {} } function activateNativeMode() { if (readerOpen) closeReader(); nativeMode.active = true; saveNativeFlag(); if (!store.bookName) { const s = loadSession(); store.bookName = (s && s.bookName) || extractBookName(document) || ''; store.bookId = (s && s.bookId) || extractBookId(location.href) || ''; } buildNativeBar(); setupNativeTapZones(); setupNativeEdgeFlip(); applyNativeStyle(); setTimeout(applyPurifyToNativePage, 100); if (!store.tocList.length) { const tocUrl = findTOCUrl(document, location.href); if (tocUrl) { store.tocUrl = tocUrl; fetchTOCList(tocUrl).then(list => { if (list && list.length >= CONFIG.tocMinCount) { store.tocList = list; log('[原生模式] 目录已加载:' + list.length + ' 章'); } }).catch(() => {}); } } lastMenuKey = ''; updateMenu(); if (settings.autoPageEnabled) startAutoPageTimer(); log('[原生模式] 已激活'); } function deactivateNativeMode() { nativeMode.active = false; clearNativeFlag(); removeNativeStyle(); restoreNativePageText(); if (nativeMode.barHost) { try { nativeMode.barHost.remove(); } catch (e) {} nativeMode.barHost = null; } if (nativeMode.tocHost) { try { nativeMode.tocHost.remove(); } catch (e) {} nativeMode.tocHost = null; } hideNativeBar(); if (autoPageTimer) { clearTimeout(autoPageTimer); autoPageTimer = null; } lastMenuKey = ''; updateMenu(); log('[原生模式] 已退出'); } let nativeBarVisible = false; let nativeBarHideTimer = null; function showNativeBar(autoHide) { if (!nativeMode.barHost) return; nativeBarVisible = true; const sh = nativeMode.barHost.shadowRoot; if (sh) { const bar = sh.querySelector('.bar'); if (bar) bar.classList.add('visible'); } if (autoHide) resetNativeBarTimer(); } function hideNativeBar() { nativeBarVisible = false; if (nativeBarHideTimer) { clearTimeout(nativeBarHideTimer); nativeBarHideTimer = null; } if (!nativeMode.barHost) return; const sh = nativeMode.barHost.shadowRoot; if (sh) { const bar = sh.querySelector('.bar'); if (bar) bar.classList.remove('visible'); } } function resetNativeBarTimer() { if (nativeBarHideTimer) clearTimeout(nativeBarHideTimer); nativeBarHideTimer = setTimeout(() => hideNativeBar(), NATIVE_BAR_AUTO_HIDE); } function toggleNativeBar() { if (nativeBarVisible) hideNativeBar(); else showNativeBar(true); } function getNativeScrollContainer() { const scrollingEl = document.scrollingElement || document.documentElement; if (scrollingEl && scrollingEl.scrollHeight > scrollingEl.clientHeight + 20) return scrollingEl; if (document.body && document.body.scrollHeight > document.body.clientHeight + 20) return document.body; const all = document.querySelectorAll('div, main, article, section'); let best = null, bestScore = 0; for (const el of all) { const cs = getComputedStyle(el); const oy = cs.overflowY; if (oy !== 'auto' && oy !== 'scroll') continue; const sh = el.scrollHeight; const ch = el.clientHeight; if (sh <= ch + 50) continue; const w = el.clientWidth; const score = (sh - ch) * w; if (score > bestScore) { bestScore = score; best = el; } } return best || scrollingEl; } function nativeScrollBy(direction) { const el = getNativeScrollContainer(); const viewH = el.clientHeight || window.innerHeight || document.documentElement.clientHeight; const curTop = el.scrollTop; const maxTop = Math.max(0, el.scrollHeight - viewH); const step = Math.round(viewH * SCROLL_STEP_RATIO); const EDGE = 8; if (direction > 0) { if (curTop >= maxTop - EDGE) { if (typeof nativeMode.goNext === 'function') nativeMode.goNext(); return; } const target = Math.min(maxTop, curTop + step); try { el.scrollTo({ top: target, behavior: 'smooth' }); } catch (e) { el.scrollTop = target; } } else { if (curTop <= EDGE) { if (typeof nativeMode.goPrev === 'function') nativeMode.goPrev(); return; } const target = Math.max(0, curTop - step); try { el.scrollTo({ top: target, behavior: 'smooth' }); } catch (e) { el.scrollTop = target; } } } const nativeTap = { startX: 0, startY: 0, startTime: 0, mouseX: 0, mouseY: 0, mouseTime: 0, touchHandled: false, lastTouchEnd: 0, mouseIgnoreClick: false, installed: false, }; function setupNativeTapZones() { if (nativeTap.installed) return; nativeTap.installed = true; window.addEventListener('touchstart', e => { if (!nativeMode.active) return; if (e.touches.length !== 1) return; const t = e.touches[0]; nativeTap.startX = t.clientX; nativeTap.startY = t.clientY; nativeTap.startTime = Date.now(); nativeTap.touchHandled = false; }, true); window.addEventListener('touchend', e => { if (!nativeMode.active) return; if (e.touches.length > 0) return; if (e.changedTouches.length !== 1) return; const t = e.changedTouches[0]; const dx = Math.abs(t.clientX - nativeTap.startX); const dy = Math.abs(t.clientY - nativeTap.startY); if (dx > 10 || dy > 10) return; if (Date.now() - nativeTap.startTime > 500) return; nativeTap.touchHandled = true; nativeTap.lastTouchEnd = Date.now(); handleNativeTap(t.clientX, t.clientY, e.target); }, true); window.addEventListener('mousedown', e => { if (!nativeMode.active) return; nativeTap.mouseX = e.clientX; nativeTap.mouseY = e.clientY; nativeTap.mouseTime = Date.now(); }, true); window.addEventListener('click', e => { if (!nativeMode.active) return; if (nativeTap.touchHandled) { nativeTap.touchHandled = false; return; } if (Date.now() - nativeTap.lastTouchEnd < 500) return; const dx = Math.abs(e.clientX - nativeTap.mouseX); const dy = Math.abs(e.clientY - nativeTap.mouseY); if (dx > 10 || dy > 10) return; if (Date.now() - nativeTap.mouseTime > 500) return; handleNativeTap(e.clientX, e.clientY, e.target); }, true); } // ==================== 原网站模式:滑到底后再滑一次 → 下一章 ==================== const nativeEdgeFlip = { installed: false, startY: 0, lastDy: 0, startAtBottom: false, }; function setupNativeEdgeFlip() { if (nativeEdgeFlip.installed) return; nativeEdgeFlip.installed = true; const EDGE = 40; const SWIPE_THRESHOLD = 30; window.addEventListener('touchstart', e => { if (!nativeMode.active) return; if (e.touches.length !== 1) return; const el = getNativeScrollContainer(); if (!el) return; const viewH = el.clientHeight || window.innerHeight || document.documentElement.clientHeight; const maxTop = Math.max(0, el.scrollHeight - viewH); const curTop = el.scrollTop; nativeEdgeFlip.startY = e.touches[0].clientY; nativeEdgeFlip.lastDy = 0; nativeEdgeFlip.startAtBottom = curTop >= maxTop - EDGE; }, { passive: true }); window.addEventListener('touchmove', e => { if (!nativeMode.active) return; if (e.touches.length !== 1) return; nativeEdgeFlip.lastDy = nativeEdgeFlip.startY - e.touches[0].clientY; }, { passive: true }); window.addEventListener('touchend', e => { if (!nativeMode.active) return; if (e.touches.length > 0) return; const wasBottom = nativeEdgeFlip.startAtBottom; const dy = nativeEdgeFlip.lastDy; nativeEdgeFlip.startAtBottom = false; nativeEdgeFlip.lastDy = 0; if (autoPaging) return; if (!wasBottom) return; const el = getNativeScrollContainer(); if (!el) return; const viewH = el.clientHeight || window.innerHeight || document.documentElement.clientHeight; const maxTop = Math.max(0, el.scrollHeight - viewH); const curTop = el.scrollTop; if (dy > SWIPE_THRESHOLD && curTop >= maxTop - EDGE) { if (typeof nativeMode.goNext === 'function') nativeMode.goNext(); } }, { passive: true }); } function handleNativeTap(x, y, target) { if (target && (target.id === 'ndr-native-bar-host' || target.id === 'ndr-native-toc-host')) return; if (nativeMode.barHost) { const r = nativeMode.barHost.getBoundingClientRect(); if (y >= r.top && y <= r.bottom) return; } if (nativeMode.tocHost) return; let el = target; if (el && el.closest) { if (el.closest('button, a, input, textarea, select, [contenteditable="true"]')) return; } try { const sel = window.getSelection(); if (sel && String(sel).trim().length > 0) return; } catch (e) {} const w = window.innerWidth || document.documentElement.clientWidth || 1; const h = window.innerHeight || document.documentElement.clientHeight || 1; const boxSize = w / 3; const cx = w / 2; const cy = h / 2; const inBox = Math.abs(x - cx) < boxSize / 2 && Math.abs(y - cy) < boxSize / 2; if (inBox) { if (boxClickTimer) { clearTimeout(boxClickTimer); boxClickTimer = null; toggleAutoPage(); } else { boxClickTimer = setTimeout(() => { boxClickTimer = null; if (!autoPaging) resetAutoPageTimer(); toggleNativeBar(); }, 280); } return; } if (settings.tapVertical) { if (!autoPaging) resetAutoPageTimer(); if (y < cy) nativeScrollBy(-1); else nativeScrollBy(1); } else { if (!autoPaging) resetAutoPageTimer(); if (x < cx) nativeScrollBy(-1); else nativeScrollBy(1); } } function buildNativeBar() { if (nativeMode.barHost) return; const host = document.createElement('div'); host.id = 'ndr-native-bar-host'; host.style.cssText = 'position:fixed;top:0;left:0;right:0;height:46px;z-index:2147483647;pointer-events:none;'; document.documentElement.appendChild(host); const sh = host.attachShadow({ mode: 'open' }); sh.innerHTML = `
未命名
`; nativeMode.barHost = host; const $ = id => sh.getElementById(id); const titleText = (function () { const cur = normalizeUrl(location.href); if (store.tocList && store.tocList.length) { for (let i = 0; i < store.tocList.length; i++) { if (normalizeUrl(store.tocList[i].url) === cur) return store.tocList[i].title; } } const h1 = document.querySelector('#chapter-title, .chapter-title, h1, h2, .title, #title'); if (h1) { const t = (h1.textContent || '').trim().replace(/\s+/g, ' '); if (t && t.length <= 60) return t; } return document.title || '未命名'; })(); $('title').textContent = titleText.length > 24 ? titleText.slice(0, 24) + '…' : titleText; $('title').title = titleText; function goPrev() { let prev = findPrevUrl(document, location.href); if (!prev && store.tocList && store.tocList.length) { const cur = normalizeUrl(location.href); const idx = store.tocList.findIndex(it => normalizeUrl(it.url) === cur); if (idx > 0) prev = store.tocList[idx - 1].url; } if (prev) { refreshNativeFlag(); location.href = prev; } else alert('没有找到上一章'); } function goNext() { let next = findNextUrl(document, location.href); if (!next && store.tocList && store.tocList.length) { const cur = normalizeUrl(location.href); const idx = store.tocList.findIndex(it => normalizeUrl(it.url) === cur); if (idx >= 0 && idx + 1 < store.tocList.length) next = store.tocList[idx + 1].url; } if (next) { refreshNativeFlag(); location.href = next; } else alert('没有找到下一章'); } nativeMode.goPrev = goPrev; nativeMode.goNext = goNext; function openNativeTOC() { if (nativeMode.tocHost) { try { nativeMode.tocHost.remove(); } catch (e) {} nativeMode.tocHost = null; return; } const tHost = document.createElement('div'); tHost.id = 'ndr-native-toc-host'; tHost.style.cssText = 'position:fixed;inset:0;z-index:2147483647;pointer-events:none;'; document.documentElement.appendChild(tHost); const tSh = tHost.attachShadow({ mode: 'open' }); const items = (store.tocList && store.tocList.length) ? store.tocList : []; const cur = normalizeUrl(location.href); const sorted = items .map((it, idx) => ({ it, idx, num: parseChapterNumber(it.title) })) .sort((a, b) => { const an = a.num, bn = b.num; if (an === null && bn === null) return a.idx - b.idx; if (an === null) return 1; if (bn === null) return -1; return an - bn; }) .map(x => x.it); let listHtml = ''; if (!sorted.length) { listHtml = '
暂无目录。
'; } else { sorted.forEach(it => { const active = normalizeUrl(it.url) === cur; listHtml += `${escapeHtml(it.title)}`; }); } tSh.innerHTML = `
目录${sorted.length} 章
${listHtml}
`; nativeMode.tocHost = tHost; const closeFn = () => { if (nativeMode.tocHost) { try { nativeMode.tocHost.remove(); } catch (e) {} nativeMode.tocHost = null; } }; tSh.getElementById('backdrop').addEventListener('click', closeFn); tSh.getElementById('close').addEventListener('click', closeFn); tSh.querySelectorAll('.item').forEach(a => { a.addEventListener('click', ev => { ev.preventDefault(); const href = a.getAttribute('href'); if (href) { refreshNativeFlag(); location.href = href; } }); }); const act = tSh.querySelector('.item.active'); if (act) act.scrollIntoView({ block: 'center' }); } function changeNativeFont(delta) { settings.fontSize = Math.max(12, Math.min(32, settings.fontSize + delta)); setSetting('fontSize', settings.fontSize); applyNativeStyle(); } function cycleNativeTheme() { const order = ['light', 'sepia', 'green', 'wood', 'blue', 'paper', 'dark']; const i = order.indexOf(settings.theme); settings.theme = order[(i + 1) % order.length]; setSetting('theme', settings.theme); applyNativeStyle(); } $('btn-toc').addEventListener('click', openNativeTOC); $('btn-prev').addEventListener('click', goPrev); $('btn-next').addEventListener('click', goNext); $('btn-font-minus').addEventListener('click', () => changeNativeFont(-1)); $('btn-font-plus').addEventListener('click', () => changeNativeFont(1)); $('btn-theme').addEventListener('click', cycleNativeTheme); $('btn-close').addEventListener('click', () => { if (confirm('退出原网站模式?')) deactivateNativeMode(); }); sh.querySelector('.bar').addEventListener('click', () => { if (nativeBarVisible) resetNativeBarTimer(); }); sh.querySelector('.bar').addEventListener('touchstart', () => { if (nativeBarVisible) resetNativeBarTimer(); }, { passive: true }); } function maybeRestoreNativeMode() { if (!isNativeSaved()) return; const s = loadSession(); if (s) { store.bookName = s.bookName || ''; store.bookId = s.bookId || ''; } activateNativeMode(); } // ==================== 脚本阅读器 ==================== let host, shadow, readerEl; let pagedWrap, pagedInner, scrollWrap, scrollInner; let tocEl, tocListEl, tocCountEl, bookTitleEl, viewportEl; let readerOpen = false; let currentIndex = -1; let loadingIndex = -1; let prepending = false; let pendingLocator = null; let pageIndex = 0, pageCount = 1, pageW = 0; const PAGE_GAP = 48; let preloadingFor = -1; function forceScrollTop() { if (!scrollWrap) return; try { scrollWrap.scrollTop = 0; if (scrollInner) scrollInner.scrollTop = 0; if (scrollInner && scrollInner.firstElementChild) { scrollInner.firstElementChild.scrollIntoView({ block: 'start', behavior: 'auto' }); } } catch (e) {} } const CSS = ` :host { all: initial; } * { box-sizing: border-box; } .reader { --bg: #f7f5f0; --fg: #2b2b2b; --dim: #8a8a8a; --border: #e4e0d7; --panel: #fff; --hover: rgba(128,128,128,.12); position: fixed; inset: 0; width: 100vw; height: 100vh; z-index: 2147483647; background: var(--bg); color: var(--fg); display: none; flex-direction: column; font-family: -apple-system, BlinkMacSystemFont, "PingFang SC", "Hiragino Sans GB", "Microsoft YaHei", sans-serif; font-size: 18px; line-height: 1.9; -webkit-font-smoothing: antialiased; text-rendering: optimizeLegibility; } .reader.open { display: flex; } .reader.theme-dark { --bg:#16171a; --fg:#c9ccd1; --dim:#6b7078; --border:#2a2c31; --panel:#1e2024; --hover:rgba(255,255,255,.08); } .reader.theme-sepia { --bg:#f4ecd8; --fg:#5b4636; --dim:#9a8b78; --border:#e0d5bd; --panel:#faf3e3; --hover:rgba(120,90,60,.1); } .reader.theme-green { --bg:#C7EDCC; --fg:#2C3E2E; --dim:#5A7A5E; --border:#AECBB3; --panel:#DCF2E0; --hover:rgba(44,62,46,.12); } .reader.theme-wood { --bg:#F5EFE6; --fg:#3E3A39; --dim:#8A8075; --border:#E3D6C8; --panel:#FAF6F0; --hover:rgba(62,58,57,.1); } .reader.theme-blue { --bg:#D9E4F5; --fg:#1F2D3D; --dim:#6B7F96; --border:#C0CEE3; --panel:#EBF2FA; --hover:rgba(31,45,61,.1); } .reader.theme-paper { --bg:#FAFAFA; --fg:#333333; --dim:#8C8C8C; --border:#E0E0E0; --panel:#FFFFFF; --hover:rgba(51,51,51,.1); } .topbar { flex: 0 0 auto; display: flex; align-items: center; gap: 2px; padding: 6px 6px; border-bottom: 1px solid var(--border); background: var(--bg); font-size: 14px; z-index: 20; } .topbar .btn { padding: 6px 7px; flex: 0 0 auto; } .book-title { flex: 1 1 auto; font-weight: 600; font-size: 13px; text-align: center; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; padding: 0 4px; color: var(--fg); min-width: 0; -webkit-user-select: none; user-select: none; -webkit-tap-highlight-color: transparent; } .btn { background: transparent; border: none; color: var(--fg); padding: 6px 10px; border-radius: 6px; cursor: pointer; font-size: 14px; font-family: inherit; line-height: 1; display: inline-flex; align-items: center; gap: 4px; transition: background .15s; } .btn:hover:not(:disabled) { background: var(--hover); } .btn:disabled { opacity: .3; cursor: default; } .viewport { flex: 1 1 auto; position: relative; overflow: hidden; cursor: pointer; -webkit-tap-highlight-color: transparent; user-select: text; -webkit-user-select: text; } .paged-wrap { height: 100%; padding: 18px 28px 18px; overflow: hidden; position: relative; } .paged-inner { position: relative; height: 100%; column-fill: auto; transition: transform .22s ease; will-change: transform; color: var(--fg); } .scroll-wrap { height: 100%; overflow-y: auto; overflow-x: hidden; scroll-behavior: auto; -webkit-overflow-scrolling: touch; } .scroll-inner { position: relative; max-width: 780px; margin: 0 auto; padding: 18px 24px 80px; } .scroll-wrap::-webkit-scrollbar { width: 8px; } .scroll-wrap::-webkit-scrollbar-thumb { background: var(--border); border-radius: 4px; } .ch-title { font-size: 1.1em; font-weight: 600; margin: 0 0 0.4em; padding-bottom: 0.15em; border-bottom: 1px solid var(--border); color: var(--fg); line-height: 1.3; } .ch-title + p { margin-top: 0; } p { margin: 0 0 1em; text-indent: 2em; word-break: break-word; overflow-wrap: anywhere; } .empty { color: var(--dim); text-align: center; padding: 60px 20px; font-size: 15px; line-height: 2; } .spinner { display: inline-block; width: 18px; height: 18px; border: 2px solid var(--border); border-top-color: var(--dim); border-radius: 50%; animation: spin .8s linear infinite; vertical-align: middle; margin-right: 8px; } @keyframes spin { to { transform: rotate(360deg); } } .toc { position: absolute; top: 0; bottom: 0; left: 0; width: 320px; max-width: 85%; background: var(--panel); border-right: 1px solid var(--border); transform: translateX(-100%); transition: transform .22s ease; display: flex; flex-direction: column; z-index: 15; } .toc.open { transform: translateX(0); } .toc-head { display: flex; align-items: center; gap: 8px; padding: 12px 14px; border-bottom: 1px solid var(--border); font-weight: 600; font-size: 14px; color: var(--fg); } .toc-count { flex: 1 1 auto; font-size: 12px; color: var(--dim); font-weight: 400; } .toc-refresh-btn { font-weight: 600; font-size: 14px; padding: 4px 8px; } .toc-head .btn.primary { background: #4a90e2; color: #fff; } .toc-head .btn.primary:hover { background: #3a7bc8; } .toc-list { flex: 1 1 auto; overflow-y: auto; padding: 6px 0; } .toc-list::-webkit-scrollbar { width: 6px; } .toc-list::-webkit-scrollbar-thumb { background: var(--border); border-radius: 3px; } .toc-item { padding: 9px 16px; cursor: pointer; font-size: 13.5px; color: var(--fg); line-height: 1.5; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; } .toc-item:hover { background: var(--hover); } .toc-item.active { color: #4a90e2; font-weight: 600; background: var(--hover); } .toc-item.loading { color: var(--dim); font-style: italic; cursor: default; } .toc-item.selectable { display: flex; align-items: center; gap: 8px; padding-left: 10px; } .toc-item.selectable input[type="checkbox"] { width: 16px; height: 16px; margin: 0; flex: 0 0 auto; accent-color: #4a90e2; cursor: pointer; } .toc-item.selectable .toc-label { flex: 1 1 auto; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; } .toc-backdrop { position: absolute; inset: 0; background: rgba(0,0,0,.3); opacity: 0; pointer-events: none; transition: opacity .22s; z-index: 14; } .toc-backdrop.open { opacity: 1; pointer-events: auto; } `; function buildReader() { host = document.createElement('div'); host.id = 'ndr-host'; host.style.cssText = 'position:fixed;inset:0;z-index:2147483647;display:none;pointer-events:none;'; (document.body || document.documentElement).appendChild(host); shadow = host.attachShadow({ mode: 'open' }); shadow.innerHTML = `
未命名
`; const $ = id => shadow.getElementById(id); readerEl = $('reader'); viewportEl = $('viewport'); pagedWrap = $('paged-wrap'); pagedInner = $('paged-inner'); scrollWrap = $('scroll-wrap'); scrollInner = $('scroll-inner'); tocEl = $('toc'); tocListEl = $('toc-list'); tocCountEl = $('toc-count'); bookTitleEl = $('book-title'); const tocBackdrop = $('toc-backdrop'); tocBackdrop.addEventListener('click', closeTOC); $('btn-close').addEventListener('click', e => { e.stopPropagation(); closeReader(); }); $('btn-toc').addEventListener('click', e => { e.stopPropagation(); toggleTOC(); }); $('btn-toc-close').addEventListener('click', e => { e.stopPropagation(); closeTOC(); }); $('btn-toc-refresh').addEventListener('click', e => { e.stopPropagation(); refreshTOCList(); }); $('btn-toc-download').addEventListener('click', e => { e.stopPropagation(); enterTOCSelectMode(); }); $('btn-toc-select-exit').addEventListener('click', e => { e.stopPropagation(); exitTOCSelectMode(); }); $('btn-toc-select-all').addEventListener('click', e => { e.stopPropagation(); selectAllTOC(true); }); $('btn-toc-select-invert').addEventListener('click', e => { e.stopPropagation(); selectAllTOC('invert'); }); $('btn-toc-do-download').addEventListener('click', e => { e.stopPropagation(); downloadSelectedChapters(); }); $('btn-prev').addEventListener('click', e => { e.stopPropagation(); gotoChapter(currentIndex - 1, false); }); $('btn-next').addEventListener('click', e => { e.stopPropagation(); gotoChapter(currentIndex + 1, false); }); $('btn-font-plus').addEventListener('click', e => { e.stopPropagation(); changeFont(1); }); $('btn-font-minus').addEventListener('click', e => { e.stopPropagation(); changeFont(-1); }); $('btn-theme').addEventListener('click', e => { e.stopPropagation(); cycleTheme(); }); $('btn-mode').addEventListener('click', e => { e.stopPropagation(); toggleMode(); }); // 长按标题栏 let titlePressTimer = null; let titleStartX = 0, titleStartY = 0; let titleFired = false; const TITLE_EDGE = 15; const TITLE_HOLD_MS = 600; function titlePressClear() { if (titlePressTimer) { clearTimeout(titlePressTimer); titlePressTimer = null; } } bookTitleEl.addEventListener('touchstart', e => { if (!readerOpen) return; if (e.touches.length !== 1) return; const t = e.touches[0]; titleStartX = t.clientX; titleStartY = t.clientY; titleFired = false; titlePressClear(); titlePressTimer = setTimeout(() => { titlePressTimer = null; titleFired = true; try { showTitlePatternUI(); } catch (err) {} }, TITLE_HOLD_MS); }, { passive: true }); bookTitleEl.addEventListener('touchmove', e => { if (!titlePressTimer) return; if (e.touches.length !== 1) { titlePressClear(); return; } const t = e.touches[0]; if (Math.abs(t.clientX - titleStartX) > TITLE_EDGE || Math.abs(t.clientY - titleStartY) > TITLE_EDGE) titlePressClear(); }, { passive: true }); bookTitleEl.addEventListener('touchend', e => { titlePressClear(); if (titleFired) { titleFired = false; e.preventDefault(); e.stopPropagation(); } }); bookTitleEl.addEventListener('mousedown', e => { if (!readerOpen) return; titleStartX = e.clientX; titleStartY = e.clientY; titleFired = false; titlePressClear(); titlePressTimer = setTimeout(() => { titlePressTimer = null; titleFired = true; try { showTitlePatternUI(); } catch (err) {} }, TITLE_HOLD_MS); }); bookTitleEl.addEventListener('mouseup', () => titlePressClear()); bookTitleEl.addEventListener('mouseleave', () => titlePressClear()); setupTapZones(); setupScrollEdgeFlip(); document.addEventListener('keydown', onKeydown, true); scrollWrap.addEventListener('scroll', () => { if (settings.mode === 'scroll') scheduleSave(); }, { passive: true }); let rzTimer = null; window.addEventListener('resize', () => { if (!readerOpen) return; clearTimeout(rzTimer); rzTimer = setTimeout(() => { if (settings.mode === 'page') relayout(); }, 150); }); applyTheme(); applyFontSize(); applyMode(); } let touchStartX = 0, touchStartY = 0, touchStartTime = 0; let touchHandled = false, lastTouchEndTime = 0; let mouseStartX = 0, mouseStartY = 0, mouseStartTime = 0; function setupTapZones() { window.addEventListener('touchstart', e => { if (!readerOpen) return; if (e.touches.length !== 1) return; const t = e.touches[0]; touchStartX = t.clientX; touchStartY = t.clientY; touchStartTime = Date.now(); touchHandled = false; }, true); window.addEventListener('touchend', e => { if (!readerOpen) return; if (e.touches.length > 0) return; if (e.changedTouches.length !== 1) return; const t = e.changedTouches[0]; const dx = Math.abs(t.clientX - touchStartX); const dy = Math.abs(t.clientY - touchStartY); if (dx > 10 || dy > 10) return; if (Date.now() - touchStartTime > 500) return; touchHandled = true; lastTouchEndTime = Date.now(); handleTapAt(t.clientX, t.clientY); }, true); window.addEventListener('mousedown', e => { if (!readerOpen) return; mouseStartX = e.clientX; mouseStartY = e.clientY; mouseStartTime = Date.now(); }, true); window.addEventListener('click', e => { if (!readerOpen) return; if (touchHandled) { touchHandled = false; return; } if (Date.now() - lastTouchEndTime < 500) return; if (mouseStartTime > 0) { const dx = Math.abs(e.clientX - mouseStartX); const dy = Math.abs(e.clientY - mouseStartY); if (dx > 10 || dy > 10) return; if (Date.now() - mouseStartTime > 500) return; } handleTapAt(e.clientX, e.clientY); }, true); } // ==================== 脚本阅读器:滚动模式滑到底后再滑一次 → 下一章 ==================== const readerEdgeFlip = { installed: false, startY: 0, lastDy: 0, startAtBottom: false, }; function setupScrollEdgeFlip() { if (readerEdgeFlip.installed) return; if (!scrollWrap) return; readerEdgeFlip.installed = true; const EDGE = 40; const SWIPE_THRESHOLD = 30; scrollWrap.addEventListener('touchstart', e => { if (!readerOpen || settings.mode !== 'scroll') return; if (e.touches.length !== 1) return; const viewH = scrollWrap.clientHeight || window.innerHeight; const maxTop = Math.max(0, scrollWrap.scrollHeight - viewH); const curTop = scrollWrap.scrollTop; readerEdgeFlip.startY = e.touches[0].clientY; readerEdgeFlip.lastDy = 0; readerEdgeFlip.startAtBottom = curTop >= maxTop - EDGE; }, { passive: true }); scrollWrap.addEventListener('touchmove', e => { if (e.touches.length !== 1) return; readerEdgeFlip.lastDy = readerEdgeFlip.startY - e.touches[0].clientY; }, { passive: true }); scrollWrap.addEventListener('touchend', e => { if (!readerOpen || settings.mode !== 'scroll') return; if (e.touches.length > 0) return; const wasBottom = readerEdgeFlip.startAtBottom; const dy = readerEdgeFlip.lastDy; readerEdgeFlip.startAtBottom = false; readerEdgeFlip.lastDy = 0; if (autoPaging) return; if (!wasBottom) return; const viewH = scrollWrap.clientHeight || window.innerHeight; const maxTop = Math.max(0, scrollWrap.scrollHeight - viewH); const curTop = scrollWrap.scrollTop; if (dy > SWIPE_THRESHOLD && curTop >= maxTop - EDGE) { gotoChapter(currentIndex + 1, false); } }, { passive: true }); } function handleTapAt(x, y) { if (tocEl.classList.contains('open')) return; const r = viewportEl.getBoundingClientRect(); if (x < r.left || x > r.right) return; if (y < r.top || y > r.bottom) return; let elAtPoint = null; try { if (shadow.elementFromPoint) elAtPoint = shadow.elementFromPoint(x, y); } catch (err) {} if (elAtPoint && elAtPoint.closest) { if (elAtPoint.closest('button, a, input, textarea, select')) return; } try { const sel = shadow.getSelection ? shadow.getSelection() : window.getSelection(); if (sel && String(sel).trim().length > 0) return; } catch (err) {} const cx = r.left + r.width / 2; const cy = r.top + r.height / 2; const boxSize = r.width / 3; const inBox = Math.abs(x - cx) < boxSize / 2 && Math.abs(y - cy) < boxSize / 2; if (inBox) { const now = Date.now(); if (now - lastReaderBoxTap < 300) { lastReaderBoxTap = 0; toggleAutoPage(); } else { lastReaderBoxTap = now; } return; } if (settings.tapVertical) { if (y < cy) tapPrev(); else tapNext(); } else { if (x < cx) tapPrev(); else tapNext(); } } function tapNext() { if (!autoPaging) resetAutoPageTimer(); if (settings.mode === 'page') pageNext(); else scrollByScreen(1); } function tapPrev() { if (!autoPaging) resetAutoPageTimer(); if (settings.mode === 'page') pagePrev(); else scrollByScreen(-1); } function scrollByScreen(direction) { if (!scrollWrap) return; const viewH = scrollWrap.clientHeight || window.innerHeight; const curTop = scrollWrap.scrollTop; const maxTop = Math.max(0, scrollWrap.scrollHeight - viewH); const step = Math.round(viewH * SCROLL_STEP_RATIO); const EDGE = 8; if (direction > 0) { if (curTop >= maxTop - EDGE) { gotoChapter(currentIndex + 1, false); return; } const target = Math.min(maxTop, curTop + step); try { scrollWrap.scrollTo({ top: target, behavior: 'smooth' }); } catch (e) { scrollWrap.scrollTop = target; } } else { if (curTop <= EDGE) { gotoChapter(currentIndex - 1, true); return; } const target = Math.max(0, curTop - step); try { scrollWrap.scrollTo({ top: target, behavior: 'smooth' }); } catch (e) { scrollWrap.scrollTop = target; } } } function applyTheme() { readerEl.classList.remove('theme-dark', 'theme-sepia', 'theme-green', 'theme-wood', 'theme-blue', 'theme-paper'); if (settings.theme === 'dark') readerEl.classList.add('theme-dark'); else if (settings.theme === 'sepia') readerEl.classList.add('theme-sepia'); else if (settings.theme === 'green') readerEl.classList.add('theme-green'); else if (settings.theme === 'wood') readerEl.classList.add('theme-wood'); else if (settings.theme === 'blue') readerEl.classList.add('theme-blue'); else if (settings.theme === 'paper') readerEl.classList.add('theme-paper'); } function applyFontSize() { readerEl.style.fontSize = settings.fontSize + 'px'; readerEl.style.lineHeight = settings.lineHeight; } function applyMode() { if (settings.mode === 'page') { pagedWrap.style.display = ''; scrollWrap.style.display = 'none'; } else { pagedWrap.style.display = 'none'; scrollWrap.style.display = ''; } } function changeFont(d) { settings.fontSize = Math.max(12, Math.min(32, settings.fontSize + d)); setSetting('fontSize', settings.fontSize); applyFontSize(); if (currentIndex >= 0 && store.chapters[currentIndex] && store.chapters[currentIndex].content) { const savedLocator = captureLocator(); renderChapter(currentIndex, false); if (savedLocator && savedLocator.length) setTimeout(() => applyLocator(savedLocator), 60); } } function cycleTheme() { const order = ['light', 'sepia', 'green', 'wood', 'blue', 'paper', 'dark']; const names = { light: '浅色', sepia: '羊皮纸', green: '豆沙绿', wood: '暖木色', blue: '静谧蓝', paper: '纸白色', dark: '暗黑' }; const i = order.indexOf(settings.theme); settings.theme = order[(i + 1) % order.length]; setSetting('theme', settings.theme); applyTheme(); if (nativeMode.active) applyNativeStyle(); showToast('主题:' + (names[settings.theme] || settings.theme)); } function toggleMode() { settings.mode = settings.mode === 'page' ? 'scroll' : 'page'; setSetting('mode', settings.mode); applyMode(); if (currentIndex >= 0 && store.chapters[currentIndex] && store.chapters[currentIndex].content) { const savedLocator = captureLocator(); renderChapter(currentIndex); if (savedLocator && savedLocator.length) setTimeout(() => applyLocator(savedLocator), 80); } } function splitSentences(text) { text = String(text || '').trim(); if (!text) return []; const out = []; let buf = ''; for (let i = 0; i < text.length; i++) { buf += text[i]; if ('。!?!?'.indexOf(text[i]) !== -1) { const s = buf.trim(); if (s) out.push(s); buf = ''; } } if (buf.trim()) out.push(buf.trim()); return out.filter(s => s.length >= 4); } function captureLocator() { if (currentIndex < 0) return []; const ch = store.chapters[currentIndex]; if (!ch || !ch.content) return []; let target = null; if (settings.mode === 'page') { const ps = pagedInner.querySelectorAll('p'); if (!ps.length) return []; const wrapRect = pagedWrap.getBoundingClientRect(); const cs = getComputedStyle(pagedWrap); const viewLeft = wrapRect.left + (parseFloat(cs.paddingLeft) || 0); const viewRight = viewLeft + pageW; let best = null, bestLeft = Infinity; for (const p of ps) { const r = p.getBoundingClientRect(); if (r.right > viewLeft - 2 && r.left < viewRight) { const d = Math.abs(r.left - viewLeft); if (d < bestLeft) { bestLeft = d; best = p; } } } if (!best) return []; const bl = best.getBoundingClientRect().left; let bt = Infinity; for (const p of ps) { const r = p.getBoundingClientRect(); if (Math.abs(r.left - bl) < 20 && r.top < bt) { bt = r.top; target = p; } } } else { const ps = scrollInner.querySelectorAll('p'); if (!ps.length) return []; const top = scrollWrap.scrollTop; for (const p of ps) if (p.offsetTop + 60 >= top) { target = p; break; } } if (!target) return []; return splitSentences((target.textContent || '').trim()).slice(0, 3); } function applyLocator(locator) { if (!locator || !locator.length) return false; const key = locator[0]; if (!key) return false; const container = settings.mode === 'page' ? pagedInner : scrollInner; const ps = container.querySelectorAll('p'); let target = null; for (const p of ps) if ((p.textContent || '').indexOf(key) !== -1) { target = p; break; } if (!target && locator[1]) for (const p of ps) if ((p.textContent || '').indexOf(locator[1]) !== -1) { target = p; break; } if (!target) return false; if (settings.mode === 'page') { const idx = Math.floor(target.offsetLeft / (pageW + PAGE_GAP)); pageIndex = Math.max(0, Math.min(pageCount - 1, idx)); applyPageTransform(); } else { scrollWrap.scrollTop = Math.max(0, target.offsetTop - 20); } return true; } let origOverflow = null; function openReader() { if (readerOpen) return; if (nativeMode.active) deactivateNativeMode(); readerOpen = true; host.style.display = 'block'; host.style.pointerEvents = 'auto'; readerEl.classList.add('open'); origOverflow = document.documentElement.style.overflow; document.documentElement.style.overflow = 'hidden'; requestAnimationFrame(() => { if (store.chapters.length === 0) renderWelcome(); else if (currentIndex >= 0 && store.chapters[currentIndex] && store.chapters[currentIndex].content) { renderChapter(currentIndex, settings.mode === 'page'); } forceScrollTop(); setTimeout(forceScrollTop, 30); setTimeout(forceScrollTop, 120); updateTOC(); updateMenu(); if (settings.autoPageEnabled) startAutoPageTimer(); }); } function closeReader() { if (!readerOpen) return; saveSessionNow(); readerOpen = false; readerEl.classList.remove('open'); host.style.pointerEvents = 'none'; host.style.display = 'none'; document.documentElement.style.overflow = origOverflow || ''; closeTOC(); if (autoPageTimer) { clearTimeout(autoPageTimer); autoPageTimer = null; } updateMenu(); } function toggleTOC() { if (tocEl.classList.contains('open')) closeTOC(); else openTOC(); } function openTOC() { tocEl.classList.add('open'); shadow.getElementById('toc-backdrop').classList.add('open'); const active = tocListEl.querySelector('.toc-item.active'); if (active) active.scrollIntoView({ block: 'center' }); } function closeTOC() { tocEl.classList.remove('open'); shadow.getElementById('toc-backdrop').classList.remove('open'); } let tocRefreshing = false; // ==================== 目录:选择章节下载 ==================== let tocSelectMode = false; let tocDownloading = false; const tocSelected = new Set(); function enterTOCSelectMode() { if (!store.tocList || !store.tocList.length) { const fallback = store.chapters .filter(c => c && c.url) .map(c => ({ title: c.title || '未命名', url: c.url })); if (!fallback.length) { alert('还没有可下载的章节。请先阅读几章,或点 ⟳ 刷新目录。'); return; } store.tocList = fallback; } tocSelectMode = true; tocSelected.clear(); shadow.getElementById('toc-head-normal').style.display = 'none'; shadow.getElementById('toc-head-select').style.display = ''; updateTOC(); updateSelectCount(); } function exitTOCSelectMode() { tocSelectMode = false; tocSelected.clear(); shadow.getElementById('toc-head-normal').style.display = ''; shadow.getElementById('toc-head-select').style.display = 'none'; updateTOC(); } function updateSelectCount() { const el = shadow.getElementById('toc-select-count'); if (el) el.textContent = `已选 ${tocSelected.size} 章`; } function selectAllTOC(mode) { if (!store.tocList) return; if (mode === 'invert') { const next = new Set(); for (const item of store.tocList) { const u = normalizeUrl(item.url); if (!tocSelected.has(u)) next.add(u); } tocSelected.clear(); for (const u of next) tocSelected.add(u); } else if (mode === true) { for (const item of store.tocList) tocSelected.add(normalizeUrl(item.url)); } else { tocSelected.clear(); } updateTOC(); updateSelectCount(); } async function downloadSelectedChapters() { if (!tocSelected.size) { alert('还没有选中任何章节。'); return; } if (tocDownloading) return; const total = tocSelected.size; if (!confirm(`确认下载选中的 ${total} 章?\n未加载的章节会依次抓取,请耐心等待。`)) return; tocDownloading = true; const tasks = store.tocList .filter(item => tocSelected.has(normalizeUrl(item.url))) .map(item => ({ url: item.url, title: item.title })); const results = []; for (let i = 0; i < tasks.length; i++) { const t = tasks[i]; let content = ''; let title = t.title; const existing = store.chapters.find(c => c && normalizeUrl(c.url) === normalizeUrl(t.url)); if (existing && existing.content) { content = existing.content; if (existing.title) title = existing.title; } else { try { const html = await gmFetch(t.url); const doc = toDoc(html, t.url); content = extractContent(doc); const tt = extractTitle(doc, 0, content); if (tt) title = tt; } catch (e) { log('下载失败:' + t.url + ' - ' + e.message); content = ''; } await sleep(300 + Math.random() * 300); } results.push({ title, content }); const cnt = shadow.getElementById('toc-select-count'); if (cnt) cnt.textContent = `下载中 ${i + 1}/${total}…`; } const bookName = store.bookName || '小说'; let text = `${bookName}\n\n`; for (const ch of results) { if (!ch.content) continue; const purified = purifyText(ch.content); text += `\n\n${ch.title || ''}\n\n${purified}\n`; } const blob = new Blob(['\ufeff' + text], { type: 'text/plain;charset=utf-8' }); const url = URL.createObjectURL(blob); const a = document.createElement('a'); a.href = url; a.download = `${bookName.replace(/[\\/:*?"<>|]/g, '_').slice(0, 80)}_已选${results.filter(c => c.content).length}章.txt`; document.body.appendChild(a); a.click(); a.remove(); setTimeout(() => URL.revokeObjectURL(url), 2000); tocDownloading = false; showToast(`✅ 已下载 ${results.filter(c => c.content).length} 章`); exitTOCSelectMode(); } async function refreshTOCList() { if (tocRefreshing) return; tocRefreshing = true; if (tocCountEl) tocCountEl.textContent = '更新中…'; try { const curCh = store.chapters[currentIndex]; if (!curCh || !curCh.doc) { alert('当前章节未加载,无法刷新目录。'); return; } let tocUrl = store.tocUrl; if (!tocUrl) { tocUrl = findTOCUrl(curCh.doc, curCh.url); if (tocUrl) store.tocUrl = tocUrl; } if (!tocUrl) { alert('找不到目录页地址。'); return; } const list = await fetchTOCList(tocUrl); if (!list || !list.length) { alert('抓取目录失败:目录为空或结构不识别。'); return; } store.tocList = list; log('[目录] 已更新,共 ' + list.length + ' 章'); showToast('✅ 目录已更新\n共 ' + list.length + ' 章'); } catch (e) { alert('更新目录失败:' + e.message); } finally { tocRefreshing = false; updateTOC(); } } function updateTOC() { if (!tocListEl) return; const frag = document.createDocumentFragment(); if (store.tocList && store.tocList.length) { const sorted = store.tocList .map((item, idx) => ({ item, idx, num: parseChapterNumber(item.title) })) .sort((a, b) => { const an = a.num, bn = b.num; if (an === null && bn === null) return a.idx - b.idx; if (an === null) return 1; if (bn === null) return -1; if (an !== bn) return an - bn; return a.idx - b.idx; }) .map(x => x.item); sorted.forEach(item => { const el = document.createElement('div'); const isActive = currentIndex >= 0 && store.chapters[currentIndex] && normalizeUrl(store.chapters[currentIndex].url) === normalizeUrl(item.url); if (tocSelectMode) { const u = normalizeUrl(item.url); el.className = 'toc-item selectable' + (isActive ? ' active' : ''); const cb = document.createElement('input'); cb.type = 'checkbox'; cb.checked = tocSelected.has(u); cb.addEventListener('change', () => { if (cb.checked) tocSelected.add(u); else tocSelected.delete(u); updateSelectCount(); }); const label = document.createElement('span'); label.className = 'toc-label'; label.textContent = item.title; el.appendChild(cb); el.appendChild(label); el.addEventListener('click', ev => { if (ev.target === cb) return; cb.checked = !cb.checked; cb.dispatchEvent(new Event('change')); }); } else { el.className = 'toc-item' + (isActive ? ' active' : ''); el.textContent = item.title; el.addEventListener('click', () => { const idx = store.chapters.findIndex(c => c && normalizeUrl(c.url) === normalizeUrl(item.url)); if (idx >= 0) gotoChapter(idx, false); else loadByUrl(item.url); closeTOC(); }); } frag.appendChild(el); }); } else { store.chapters.forEach((ch, i) => { if (!ch) return; const item = document.createElement('div'); item.className = 'toc-item' + (i === currentIndex ? ' active' : ''); item.textContent = ch.title || `第${i + 1}条`; item.addEventListener('click', () => { gotoChapter(i, false); closeTOC(); }); frag.appendChild(item); }); if (loadingIndex >= 0) { const item = document.createElement('div'); item.className = 'toc-item loading'; item.textContent = '加载中…'; frag.appendChild(item); } } tocListEl.innerHTML = ''; tocListEl.appendChild(frag); const total = store.tocList && store.tocList.length ? store.tocList.length : store.chapters.filter(c => c && c.content).length; tocCountEl.textContent = `${total} 章${store.finished ? ' · 完' : ''}`; } function contentToHtml(text, title) { const lines = text.split('\n').map(l => l.trim()).filter(Boolean); let startIdx = 0; if (lines.length && title && lines[0].indexOf(title) === 0) startIdx = 1; const body = lines.slice(startIdx); return body.map(l => `

${escapeHtml(l)}

`).join(''); } function renderWelcome() { const html = `
📖 还没有内容

请点击油猴图标 →「📖 从本章开始阅读」
`; pagedInner.innerHTML = html; scrollInner.innerHTML = html; currentIndex = -1; updateTitleBar(); updateTOC(); } function renderLoading(msg) { const html = `
${escapeHtml(msg)}
`; if (settings.mode === 'page') pagedInner.innerHTML = html; else scrollInner.innerHTML = html; updateTitleBar(); } function renderChapter(i, toLastPage) { if (i < 0 || i >= store.chapters.length) return; const ch = store.chapters[i]; if (!ch || !ch.content) return; currentIndex = i; const purified = purifyText(ch.content); const titleHtml = ch.title ? `

${escapeHtml(ch.title)}

` : ''; const html = `${titleHtml}${contentToHtml(purified, ch.title)}`; const locatorToApply = pendingLocator; pendingLocator = null; if (settings.mode === 'page') { pagedInner.innerHTML = html; pagedWrap.style.display = ''; scrollWrap.style.display = 'none'; pageIndex = 0; requestAnimationFrame(() => { relayout(); if (locatorToApply) applyLocator(locatorToApply); else if (toLastPage && pageCount > 1) { pageIndex = pageCount - 1; applyPageTransform(); } scheduleSave(); }); } else { scrollInner.innerHTML = html; scrollWrap.style.display = ''; pagedWrap.style.display = 'none'; forceScrollTop(); requestAnimationFrame(() => { forceScrollTop(); if (locatorToApply) applyLocator(locatorToApply); else { setTimeout(forceScrollTop, 30); setTimeout(forceScrollTop, 120); setTimeout(forceScrollTop, 300); } scheduleSave(); }); } updateTitleBar(); updateTOC(); schedulePreload(); if (settings.autoPageEnabled) resetAutoPageTimer(); } function schedulePreload() { setTimeout(preloadNext, 50); } async function preloadNext() { if (!readerOpen) return; if (store.fetching) return; if (store.finished) return; if (currentIndex < 0) return; const myIdx = currentIndex; const nextIdx = myIdx + 1; if (store.chapters[nextIdx] && store.chapters[nextIdx].content) return; if (preloadingFor === nextIdx) return; preloadingFor = nextIdx; try { const curCh = store.chapters[myIdx]; if (!curCh || !curCh.doc) return; const result = await resolveNextUrl(curCh.doc, curCh.url, curCh.content); if (!result || !result.url || result.ended) return; if (!readerOpen) return; if (currentIndex !== myIdx) return; if (store.chapters[nextIdx] && store.chapters[nextIdx].content) return; const html = await gmFetch(result.url); const doc = toDoc(html, result.url); const content = extractContent(doc); const title = extractTitle(doc, nextIdx, content); const bookName = extractBookName(doc); if (store.chapters[nextIdx] && store.chapters[nextIdx].content) return; store.chapters[nextIdx] = { title, content, url: result.url, doc }; if (!store.bookName && bookName) store.bookName = bookName; if (!store.bookId) store.bookId = extractBookId(result.url); log('[预加载] 下一章已就绪:' + title); } catch (e) { log('[预加载] 失败:' + e.message); } finally { if (preloadingFor === nextIdx) preloadingFor = -1; } } async function gotoChapter(i, toLastPage) { if (!autoPaging) resetAutoPageTimer(); if (i >= store.chapters.length) { const last = store.chapters[store.chapters.length - 1]; if (!last) return; if (store.finished) return; await appendChapter(last.url, last.doc, toLastPage); return; } if (i < 0) { const first = store.chapters[0]; if (!first) return; await prependChapterFromDOM(first, toLastPage); return; } saveSessionNow(); pendingLocator = null; if (store.chapters[i] && store.chapters[i].content) { renderChapter(i, toLastPage); } else { await ensureChapter(i, { toLastPage: toLastPage }); } } async function appendChapter(prevUrl, prevDoc, toLastPage) { if (loadingIndex >= 0) return; loadingIndex = store.chapters.length; renderLoading('正在查找下一章…'); updateTOC(); try { const prevContent = store.chapters[store.chapters.length - 1].content; const result = await resolveNextUrl(prevDoc, prevUrl, prevContent); if (result && result.url) { const html = await gmFetch(result.url); const doc = toDoc(html, result.url); const content = extractContent(doc); const title = extractTitle(doc, store.chapters.length, content); const bookName = extractBookName(doc); const entry = { title, content, url: result.url, doc }; store.chapters.push(entry); if (!store.bookName && bookName) store.bookName = bookName; if (!store.bookId) store.bookId = extractBookId(result.url); loadingIndex = -1; renderChapter(store.chapters.length - 1, toLastPage); updateMenu(); } else if (result && result.ended) { loadingIndex = -1; store.finished = true; log('[下一章] 判定已完结'); renderChapter(currentIndex, false); updateTitleBar(); updateTOC(); updateMenu(); if (typeof GM_notification === 'function') { try { GM_notification({ title: '《' + (store.bookName || '本书') + '》已读完', text: '已经到最后一章了', timeout: 4000, }); } catch (e) {} } } else { loadingIndex = -1; log('找不到下一章'); renderChapter(currentIndex, false); alert('找不到下一章。可能是网站结构特殊,或网络异常。\n可以尝试:\n1. 打开目录,手动点下一章\n2. 检查网络'); } } catch (e) { loadingIndex = -1; log('加载下一章失败:' + e.message); renderChapter(currentIndex, false); } } async function prependChapterFromDOM(firstCh, toLastPage) { if (prepending) return; prepending = true; saveSessionNow(); pendingLocator = null; renderLoading('正在加载上一章…'); try { let prevUrl = await resolvePrevUrl(firstCh.doc, firstCh.url); if (!prevUrl) { prepending = false; log('找不到上一章'); renderChapter(currentIndex, false); return; } const html = await gmFetch(prevUrl); const doc = toDoc(html, prevUrl); const content = extractContent(doc); const title = extractTitle(doc, 0, content); const bookName = extractBookName(doc); const entry = { title, content, url: prevUrl, doc }; store.chapters.unshift(entry); if (currentIndex >= 0) currentIndex++; if (!store.bookName && bookName) store.bookName = bookName; if (!store.bookId) store.bookId = extractBookId(prevUrl); prepending = false; renderChapter(0, toLastPage); updateMenu(); } catch (e) { prepending = false; log('加载上一章失败:' + e.message); renderChapter(currentIndex, false); } } async function loadByUrl(url) { url = normalizeUrl(url); const idx = store.chapters.findIndex(c => c && normalizeUrl(c.url) === url); if (idx >= 0) { gotoChapter(idx, false); return; } loadingIndex = store.chapters.length; renderLoading('正在加载…'); updateTOC(); try { const html = await gmFetch(url); const doc = toDoc(html, url); const content = extractContent(doc); const title = extractTitle(doc, store.chapters.length, content); const bookName = extractBookName(doc); const entry = { title, content, url, doc }; store.chapters.push(entry); if (!store.bookName && bookName) store.bookName = bookName; if (!store.bookId) store.bookId = extractBookId(url); loadingIndex = -1; renderChapter(store.chapters.length - 1, false); updateMenu(); } catch (e) { loadingIndex = -1; log('加载失败:' + e.message); renderLoading('加载失败:' + e.message); } } function relayout() { if (settings.mode !== 'page') return; if (!pagedInner.innerHTML) return; const cs = getComputedStyle(pagedWrap); const padX = (parseFloat(cs.paddingLeft) || 0) + (parseFloat(cs.paddingRight) || 0); const padY = (parseFloat(cs.paddingTop) || 0) + (parseFloat(cs.paddingBottom) || 0); const innerW = Math.max(100, pagedWrap.clientWidth - padX); const innerH = Math.max(100, pagedWrap.clientHeight - padY); pagedInner.style.columnWidth = innerW + 'px'; pagedInner.style.columnGap = PAGE_GAP + 'px'; pagedInner.style.height = innerH + 'px'; void pagedInner.offsetWidth; pageW = innerW; const totalW = pagedInner.scrollWidth; pageCount = Math.max(1, Math.round((totalW + PAGE_GAP) / (innerW + PAGE_GAP))); if (pageIndex >= pageCount) pageIndex = pageCount - 1; if (pageIndex < 0) pageIndex = 0; applyPageTransform(); } function applyPageTransform() { const x = -pageIndex * (pageW + PAGE_GAP); pagedInner.style.transform = `translateX(${x}px)`; updateTitleBar(); scheduleSave(); } function pageNext() { if (settings.mode !== 'page') return; if (pageIndex < pageCount - 1) { pageIndex++; applyPageTransform(); if (settings.autoPageEnabled) resetAutoPageTimer(); } else { gotoChapter(currentIndex + 1, false); } } function pagePrev() { if (settings.mode !== 'page') return; if (pageIndex > 0) { pageIndex--; applyPageTransform(); if (settings.autoPageEnabled) resetAutoPageTimer(); } else { gotoChapter(currentIndex - 1, true); } } function updateTitleBar() { if (!bookTitleEl) return; const ch = store.chapters[currentIndex]; const isLast = store.finished && currentIndex >= store.chapters.length - 1; let s; if (ch && ch.content) { s = ch.title || '(未识别标题)'; if (settings.mode === 'page' && pageCount > 1) s += ` · ${pageIndex + 1}/${pageCount}`; if (isLast) s += ' · 完'; else if (store.fetching) s += ' · 缓存中'; if (settings.autoPageEnabled) s += ' ⏯'; } else if (store.fetching) { s = '加载中…'; } else { s = store.bookName || '未命名'; } bookTitleEl.textContent = s; bookTitleEl.title = (store.bookName ? `《${store.bookName}》 ` : '') + s + '\n(长按可设置标题识别格式)'; const prev = shadow.getElementById('btn-prev'); const next = shadow.getElementById('btn-next'); if (prev) prev.disabled = currentIndex <= 0 && store.chapters.length <= 1; if (next) next.disabled = isLast; } function onKeydown(e) { if (!readerOpen) return; const tag = (e.target && e.target.tagName || '').toLowerCase(); if (tag === 'input' || tag === 'textarea') return; if (!autoPaging) resetAutoPageTimer(); switch (e.key) { case 'Escape': if (tocEl.classList.contains('open')) closeTOC(); else closeReader(); e.preventDefault(); break; case 'ArrowRight': if (settings.mode === 'page') pageNext(); else scrollByScreen(1); e.preventDefault(); break; case 'ArrowLeft': if (settings.mode === 'page') pagePrev(); else scrollByScreen(-1); e.preventDefault(); break; case 'ArrowDown': case 'PageDown': case ' ': if (settings.mode === 'scroll') { scrollByScreen(1); e.preventDefault(); } else if (e.key === ' ') { pageNext(); e.preventDefault(); } break; case 'ArrowUp': case 'PageUp': if (settings.mode === 'scroll') { scrollByScreen(-1); e.preventDefault(); } break; case 'Home': gotoChapter(0, false); e.preventDefault(); break; case 'End': if (store.chapters.length) gotoChapter(store.chapters.length - 1, false); e.preventDefault(); break; } } async function ensureChapter(i, opts) { opts = opts || {}; if (i < 0) return; if (i === loadingIndex) return; const cur = store.chapters[i]; if (cur && cur.content) { renderChapter(i, opts.toLastPage); return; } let url = cur ? cur.url : null; if (!url && opts.url) url = opts.url; if (!url) { renderLoading(`第 ${i + 1} 条无法定位`); return; } loadingIndex = i; renderLoading('正在加载…'); updateTOC(); try { const html = await gmFetch(url); const doc = toDoc(html, url); const content = extractContent(doc); const title = extractTitle(doc, i, content); const bookName = extractBookName(doc); const entry = { title, content, url, doc }; if (store.chapters[i]) Object.assign(store.chapters[i], entry); else store.chapters[i] = entry; if (!store.bookName && bookName) store.bookName = bookName; if (!store.bookId) store.bookId = extractBookId(url); loadingIndex = -1; renderChapter(i, opts.toLastPage); updateMenu(); } catch (e) { loadingIndex = -1; log('加载失败:' + e.message); renderLoading('加载失败:' + e.message); } } function openFromCurrent() { if (nativeMode.active) deactivateNativeMode(); const url = normalizeUrl(location.href); startReading(url, { sessionId: genSessionId() }); } function resumeReading(session) { if (!session || !session.url) { const s = loadSession(); if (!s || !s.url) { alert('没有可恢复的阅读进度。'); return; } session = s; } if (nativeMode.active) deactivateNativeMode(); startReading(session.url, { sessionId: session.id, locator: session.locator || null, bookName: session.bookName || '', }); } async function startReading(url, opts) { opts = opts || {}; currentSessionId = opts.sessionId || genSessionId(); store.bookName = opts.bookName || ''; store.bookId = extractBookId(url); store.tocUrl = ''; store.tocList = []; store.chapters = []; store.fetching = false; store.finished = false; store.stopped = false; currentIndex = -1; loadingIndex = -1; prepending = false; pendingLocator = opts.locator || null; preloadingFor = -1; if (settings.autoPageEnabled) stopAutoPage(); openReader(); renderLoading('正在加载…'); updateTOC(); updateMenu(); await ensureChapter(0, { url: url }); } async function startFullFetch(startUrl, userBookName) { if (store.fetching) return; if (nativeMode.active) deactivateNativeMode(); if (settings.autoPageEnabled) stopAutoPage(); currentSessionId = genSessionId(); store.bookName = userBookName || ''; store.bookId = extractBookId(startUrl); store.tocUrl = ''; store.tocList = []; store.chapters = []; store.fetching = true; store.finished = false; store.stopped = false; currentIndex = -1; loadingIndex = -1; prepending = false; pendingLocator = null; preloadingFor = -1; openReader(); renderLoading('正在抓取…'); updateTOC(); updateMenu(); let url = normalizeUrl(startUrl); const visited = new Set(); let prevDoc = null; try { while (url && store.chapters.length < CONFIG.maxChapters && !store.stopped) { const key = normalizeUrl(url); if (visited.has(key)) { log('检测到循环链接,停止'); break; } visited.add(key); let entry = null; try { const html = await gmFetch(url); const doc = toDoc(html, url); const content = extractContent(doc); const title = extractTitle(doc, store.chapters.length, content); const bookName = extractBookName(doc); entry = { title, content, url, doc }; if (!store.bookName && bookName) store.bookName = bookName; } catch (e) { log('请求失败:' + e.message + ',2 秒后重试'); await sleep(2000); try { const html = await gmFetch(url); const doc = toDoc(html, url); const content = extractContent(doc); const title = extractTitle(doc, store.chapters.length, content); const bookName = extractBookName(doc); entry = { title, content, url, doc }; if (!store.bookName && bookName) store.bookName = bookName; } catch (e2) { log('重试仍失败:' + e2.message); } } if (entry) { store.chapters.push(entry); if (currentIndex === -1) renderChapter(0); updateTOC(); updateTitleBar(); updateMenu(); prevDoc = entry.doc; } if (store.stopped) break; const curContent = entry ? entry.content : ''; const result = prevDoc ? await resolveNextUrl(prevDoc, url, curContent) : null; if (result && result.url) { url = result.url; } else if (result && result.ended) { log('已完结,停止'); store.finished = true; break; } else { log('找不到下一章,停止'); break; } await sleep(CONFIG.requestDelay + Math.random() * 400); } } catch (e) { log('抓取出错:' + e.message); } store.fetching = false; if (!store.finished) store.finished = true; updateTOC(); updateTitleBar(); updateMenu(); scheduleSave(); if (typeof GM_notification === 'function') { try { GM_notification({ title: '小说抓取完成', text: `《${store.bookName}》共 ${store.chapters.length} 章`, timeout: 6000, }); } catch (e) {} } } function exportTxt() { const chapters = store.chapters.filter(c => c && c.content); if (chapters.length === 0) { alert('还没有任何已加载的章节。'); return; } let text = `${store.bookName || '小说'}\n\n`; for (const ch of chapters) { const purified = purifyText(ch.content); text += `\n\n${ch.title || ''}\n\n${purified}\n`; } const blob = new Blob(['\ufeff' + text], { type: 'text/plain;charset=utf-8' }); const url = URL.createObjectURL(blob); const a = document.createElement('a'); a.href = url; a.download = `${(store.bookName || '小说').replace(/[\\/:*?"<>|]/g, '_').slice(0, 80)}.txt`; document.body.appendChild(a); a.click(); a.remove(); setTimeout(() => URL.revokeObjectURL(url), 2000); } // ==================== 标题识别格式 UI ==================== function reidentifyCurrentTitle() { if (currentIndex < 0) return; const ch = store.chapters[currentIndex]; if (!ch || !ch.doc || !ch.content) return; const newTitle = extractTitle(ch.doc, currentIndex, ch.content); if (newTitle) ch.title = newTitle; updateTitleBar(); updateTOC(); showToast('已重新识别标题:\n' + (ch.title || '(无)')); } function showTitlePatternUI() { while (true) { const list = loadTitlePatterns(); let msg = '📖 标题识别格式\n\n'; msg += '按顺序尝试匹配,正文优先,找不到再去页面元素找。\n'; msg += '输入一个例子就自动生成规则,例如输入:第1章、15【、楔子。\n'; msg += '例子里的数字段和标点(中英文逗号/句号等)都会自动通配。\n\n'; if (!list.length) { msg += '(还没有格式)\n\n'; } else { list.forEach((p, i) => { const mark = p.enabled ? '✅' : '⬜'; msg += `${i + 1}. ${mark} ${p.example}\n`; }); msg += '\n'; } msg += '──────────────────\n'; msg += '输入例子 → 添加规则(如:第1章)\n'; msg += '数字 → 开/关某条(如 1)\n'; msg += '数字+s → 删除某条(如 1s)\n'; msg += '输入 重置 → 恢复默认\n'; msg += '直接确定 → 退出'; const input = prompt(msg, ''); if (input === null) return; const txt = input.trim(); if (!txt) return; if (/^重置$/.test(txt)) { if (confirm('恢复默认标题识别格式?')) { saveTitlePatterns(JSON.parse(JSON.stringify(DEFAULT_TITLE_PATTERNS))); reidentifyCurrentTitle(); } continue; } let m; if ((m = txt.match(/^(\d+)s$/i))) { const idx = parseInt(m[1], 10) - 1; if (idx >= 0 && idx < list.length) { if (confirm('删除「' + list[idx].example + '」?')) { list.splice(idx, 1); saveTitlePatterns(list); reidentifyCurrentTitle(); } } continue; } if (/^\d+$/.test(txt)) { const idx = parseInt(txt, 10) - 1; if (idx >= 0 && idx < list.length) { list[idx].enabled = !list[idx].enabled; saveTitlePatterns(list); reidentifyCurrentTitle(); } continue; } const pattern = exampleToPattern(txt); if (!pattern) { alert('无法从这个例子生成规则,换一个试试。'); continue; } if (list.some(p => p.example === txt)) { alert('这个例子已经存在了。'); continue; } try { new RegExp(pattern); } catch (e) { alert('生成的正则有问题:' + e.message); continue; } list.push({ example: txt, pattern, enabled: true }); saveTitlePatterns(list); reidentifyCurrentTitle(); } } // ==================== 净化文字管理 UI ==================== function showPurifyUI() { while (true) { const list = loadPurifyList(); let msg = '🧹 净化文字管理\n\n'; msg += '作用:正文里"包含"这些关键词的**那几个字**会被删除。\n'; msg += '(是删字,不是删行/删块)\n'; msg += '改规则会立即应用到当前页面。\n\n'; if (!list.length) { msg += '(还没有规则)\n\n'; } else { list.forEach((kw, i) => { msg += `${i + 1}. ${kw}\n`; }); msg += '\n'; } msg += '──────────────────\n'; msg += '输入文字 → 添加规则\n'; msg += '数字+s → 删除规则(如 1s)\n'; msg += '输入"清空" → 删除全部\n'; msg += '直接确定 → 退出'; const input = prompt(msg, ''); if (input === null) return; const txt = input.trim(); if (!txt) return; if (/^清空$/.test(txt)) { if (confirm('确认清空所有净化规则?')) { savePurifyList([]); lastMenuKey = ''; updateMenu(); reapplyPurifyToReader(); showToast('✅ 已清空净化规则'); } continue; } let m; if ((m = txt.match(/^(\d+)s$/i))) { const idx = parseInt(m[1], 10) - 1; if (idx >= 0 && idx < list.length) { list.splice(idx, 1); savePurifyList(list); lastMenuKey = ''; updateMenu(); reapplyPurifyToReader(); showToast('✅ 已删除规则'); } continue; } if (list.indexOf(txt) === -1) { list.push(txt); savePurifyList(list); lastMenuKey = ''; updateMenu(); reapplyPurifyToReader(); showToast('✅ 已添加净化规则\n' + txt); } else { showToast('⚠️ 规则已存在'); } } } // ==================== 云备份(TextDB) ==================== function getCloudKey() { try { return String(GM_getValue(CLOUD_KEY_NAME) || '').trim(); } catch (e) { return ''; } } function setCloudKey(v) { try { GM_setValue(CLOUD_KEY_NAME, String(v || '').trim()); } catch (e) {} } function packAllConfig() { const data = { version: 1, time: Date.now(), titlePatterns: GM_getValue(TITLE_PATTERNS_KEY) || '', purifyList: GM_getValue(PURIFY_KEY) || '', recent: GM_getValue(RECENT_KEY) || '', fontSize: getSetting('fontSize', 18), lineHeight: getSetting('lineHeight', 1.9), theme: getSetting('theme', 'light'), mode: getSetting('mode', 'page'), tapVertical: getSetting('tapVertical', false) ? true : false, autoPageEnabled: getSetting('autoPageEnabled', false) ? true : false, autoPageInterval: getSetting('autoPageInterval', 10), }; return data; } function unpackAllConfig(data) { if (!data || typeof data !== 'object') return false; try { if (typeof data.titlePatterns === 'string' && data.titlePatterns) { GM_setValue(TITLE_PATTERNS_KEY, data.titlePatterns); } if (typeof data.purifyList === 'string' && data.purifyList) { GM_setValue(PURIFY_KEY, data.purifyList); } if (typeof data.recent === 'string' && data.recent) { GM_setValue(RECENT_KEY, data.recent); } if (typeof data.fontSize === 'number') setSetting('fontSize', data.fontSize); if (typeof data.lineHeight === 'number') setSetting('lineHeight', data.lineHeight); if (typeof data.theme === 'string') setSetting('theme', data.theme); if (typeof data.mode === 'string') setSetting('mode', data.mode); if (typeof data.tapVertical === 'boolean') setSetting('tapVertical', data.tapVertical); if (typeof data.autoPageEnabled === 'boolean') setSetting('autoPageEnabled', data.autoPageEnabled); if (typeof data.autoPageInterval === 'number') setSetting('autoPageInterval', data.autoPageInterval); return true; } catch (e) { return false; } } function cloudUpload(cfg, cb) { const key = getCloudKey(); if (!key) { cb && cb('nokey'); return; } const jsonStr = JSON.stringify(cfg); const url = 'https://api.textdb.online/update?key=' + encodeURIComponent(key) + '&value=' + encodeURIComponent(jsonStr); GM_xmlhttpRequest({ method: 'GET', url: url, timeout: 20000, onload: res => { if (res.status === 200) cb && cb('ok'); else cb && cb('fail', res.status); }, onerror: () => cb && cb('error'), ontimeout: () => cb && cb('timeout'), }); } function cloudDownload(key, cb) { const url = 'https://textdb.online/' + encodeURIComponent(key); GM_xmlhttpRequest({ method: 'GET', url: url, timeout: 20000, onload: res => { if (res.status === 200 && res.responseText) cb && cb('ok', res.responseText); else if (res.status === 404) cb && cb('notfound'); else cb && cb('fail', res.status); }, onerror: () => cb && cb('error'), ontimeout: () => cb && cb('timeout'), }); } function showCloudUI() { while (true) { const key = getCloudKey(); let msg = '☁️ 云备份\n\n'; msg += '当前 Key:' + (key || '(未设置)') + '\n\n'; msg += '──────────────────\n'; msg += '1. 设置 / 更换 Key\n'; msg += '2. 上传(本地 → 云)\n'; msg += '3. 同步(云 → 本地)\n'; msg += '0. 退出'; const input = prompt(msg, ''); if (input === null) return; const t = input.trim(); if (!t || t === '0') return; if (t === '1') { const cur = getCloudKey(); const nk = prompt('输入云备份 Key:\n(自己设一个好记的,别用 123456)\n\n注意:数据会公开存在 TextDB,任何人知道 Key 都能看到。', cur); if (nk === null) continue; const nv = nk.trim(); if (!nv) { alert('Key 不能为空。'); continue; } setCloudKey(nv); showToast('✅ Key 已设置'); continue; } if (t === '2') { if (!key) { alert('请先设置 Key。'); continue; } if (!confirm('确定把本地配置上传到云吗?\n云端现有内容会被覆盖。')) continue; const cfg = packAllConfig(); cloudUpload(cfg, (r, st) => { if (r === 'ok') showToast('✅ 已上传到云'); else if (r === 'nokey') alert('请先设置 Key。'); else if (r === 'timeout') alert('上传超时,请检查网络。'); else alert('上传失败' + (st ? '(' + st + ')' : '') + '。'); }); continue; } if (t === '3') { if (!key) { alert('请先设置 Key。'); continue; } if (!confirm('确定从云同步到本地吗?\n本地现有配置会被覆盖。')) continue; cloudDownload(key, (r, data) => { if (r === 'ok') { let parsed = null; try { parsed = JSON.parse(data); } catch (e) {} if (!parsed) { alert('云上的数据格式不对,无法解析。'); return; } const ok = unpackAllConfig(parsed); if (ok) { showToast('✅ 已同步到本地,请刷新页面'); } else { alert('同步失败:数据结构不正确。'); } } else if (r === 'notfound') alert('云端没有这个 Key 的数据,请先上传。'); else if (r === 'timeout') alert('下载超时,请检查网络。'); else alert('同步失败' + (r === 'fail' ? '(' + data + ')' : '') + '。'); }); continue; } alert('输入不识别,请输入 1、2、3 或 0。'); } } // ==================== 菜单 ==================== const menuIds = {}; let lastMenuKey = ''; function updateMenu() { const recent = loadRecentSessions(); const hasLoaded = store.chapters.some(c => c && c.content); const recentKey = recent.map(s => s.id + '@' + (s.time || 0)).join(','); const key = [ store.fetching, store.chapters.length, store.finished, store.stopped, readerOpen, hasLoaded, store.tocList.length, nativeMode.active, settings.tapVertical ? 1 : 0, settings.autoPageEnabled ? 1 : 0, settings.autoPageInterval, settings.theme, recentKey ].join('|'); if (key === lastMenuKey) return; lastMenuKey = key; if (typeof GM_unregisterMenuCommand === 'function') { Object.values(menuIds).forEach(id => { try { GM_unregisterMenuCommand(id); } catch (e) {} }); } Object.keys(menuIds).forEach(k => delete menuIds[k]); const ZW = '\u200b'; const pfx = pos => ZW.repeat(Math.max(0, 20 - pos)); const reg = (pos, label, fn) => { try { return GM_registerMenuCommand(pfx(pos) + label, fn); } catch (e) { return null; } }; menuIds.open = reg(1, '📖 从本章开始阅读', openFromCurrent); if (nativeMode.active) { menuIds.exitNative = reg(2, '🚪 退出原网站模式', deactivateNativeMode); } else { menuIds.openNative = reg(2, '📄 用原网站模式阅读本章', activateNativeMode); } menuIds.purify = reg(3, '🧹 净化文字管理', showPurifyUI); recent.slice(0, MAX_RECENT).forEach((s, i) => { const prog = makeProgressLabel(s); menuIds['resume' + i] = reg(4 + i, '📖 ' + prog, () => resumeReading(s)); }); menuIds.flip = reg(12, settings.tapVertical ? '↕ 上下翻页(上半=上一页,下半=下一页)' : '↔ 左右翻页(左=上一页,右=下一页)', toggleTapDirection ); if (readerOpen || nativeMode.active) { const autoLabel = settings.autoPageEnabled ? `⏯ 自动翻页(每 ${settings.autoPageInterval} 秒)` : '⏯ 自动翻页(关)'; menuIds.autoPage = reg(13, autoLabel, toggleAutoPage); } menuIds.cloud = reg(14, '☁️ 云备份', showCloudUI); menuIds.status = reg(15, '📊 状态', showStatus); if (store.fetching) { menuIds.prog = reg(16, `⏳ 全本抓取中… 已 ${store.chapters.length} 章`, () => {}); menuIds.stop = reg(17, '⏹ 停止抓取', () => { store.stopped = true; }); } else { menuIds.fetchFirst = reg(16, '📥 从第一章全本抓取…', () => { const url = prompt('输入【第一章】网址(可留空使用当前页):', location.href); if (!url || !url.trim()) return; const book = prompt('书名(可留空自动识别):', ''); startFullFetch(url.trim(), (book || '').trim()); }); menuIds.fetchCur = reg(17, '📥 以当前页为第一章抓取…', () => { const url = location.href; if (!url) return; const book = prompt('书名(可留空自动识别):', ''); startFullFetch(url, (book || '').trim()); }); } if (hasLoaded) { menuIds.export = reg(18, '💾 导出已加载章节 TXT', exportTxt); } menuIds.help = reg(19, '❓ 使用说明', showHelp); } function showHelp() { const text = [ '📖 小说阅读器 · 使用说明', '', '【一、基本用法】', '1. 打开任意小说章节页', '2. 点油猴图标 →「📖 从本章开始阅读」', '3. 阅读器打开后,从当前章开始阅读', '4. 往后翻页会自动抓取下一章', '5. 关闭阅读器:点顶栏的 ✕', '', '【二、翻页操作】', '· 左右翻页(默认):点左半屏上一页,点右半屏下一页', '· 上下翻页:点上半屏上一页,点下半屏下一页', '· 方向可在菜单里切换', '· 双击屏幕中央方块 → 开启/关闭自动翻页', '· 键盘:← → 翻页,空格翻页,Esc 关闭', '· 点击顶栏 ◐ 按钮 → 循环切换主题', '· 主题顺序:浅色 → 羊皮纸 → 豆沙绿 → 暖木色 → 静谧蓝 → 纸白色 → 暗黑', '· 滚动模式滑到底部后再向上滑一次 → 自动下一章', '· 原网站模式滑到底部后再向上滑一次 → 自动下一章', '', '【三、目录】', '· 点顶栏 ☰ 打开目录', '· 目录顶部「⟳ 目录」可点击 → 重新抓取完整目录', '· 若目录页只显示最新章节,会自动探测"查看完整目录"', '· 目录顶部「⬇」→ 进入选择模式,可勾选章节批量下载为 TXT', '· 选择模式:全选 / 反选 / 下载 / 退出', '· 没刷新目录时,也能下载"已加载章节"', '', '【四、自动翻页】', '· 双击屏幕中央方块开/关', '· 开启后屏幕会保持常亮,不会自动熄屏', '', '【五、净化文字】', '· 菜单 →「🧹 净化文字管理」', '· 输入文字 → 添加规则', '· 正文里"包含"这段文字的那几个字会被删除(删字,不删行)', '· 改规则会立即应用(阅读器 + 原网站模式)', '· 导出 TXT 时同样会净化', '', '【六、标题识别格式】', '· 长按阅读器顶栏的标题(约 0.6 秒)→ 打开设置', '· 每一行显示:编号、开关、例子', '· 输入例子 → 自动添加新规则(如:第1章、15【、楔子、85,86.)', '· 例子里的数字段、标点都会自动通配(中英文逗号/句号等都认)', '· 输入数字 → 开/关某条(如 1)', '· 输入 数字+s → 删除某条(如 1s)', '· 输入 重置 → 恢复默认格式', '· 正文优先匹配,匹配不上再去页面元素(h1 等)找', '', '【七、云备份】', '· 菜单 →「☁️ 云备份」', '· 1. 设置 / 更换 Key(自己设,好记的)', '· 2. 上传(本地配置覆盖到云)', '· 3. 同步(云端覆盖到本地,需刷新页面)', '· 备份内容:标题规则、净化词、阅读历史、字号、主题、翻页方向等', '· 注意:数据公开存在 TextDB,任何人知道 Key 都能看到', '', '【八、菜单功能】', '📖 从本章开始阅读', '📄 用原网站模式阅读本章 / 🚪 退出原网站模式', '🧹 净化文字管理', '📖 最近阅读记录(最多 8 本)', '↔ / ↕ 切换翻页方向', '⏯ 自动翻页(间隔可设 2~600 秒)', '☁️ 云备份', '📊 状态', '📥 从第一章全本抓取…', '📥 以当前页为第一章抓取…', '💾 导出已加载章节 TXT', '❓ 使用说明(本页)', '', '【九、原网站模式】', '· 在原网站上加一层悬浮工具条', '· 净化文字在原网站模式下同样生效', '· 退出:点悬浮条 ✕ 或菜单「🚪 退出原网站模式」', '', '【十、限制说明】', '· 阅读历史:只在脚本阅读器里保存', '· 原网站模式:不保存进度', '· 屏幕常亮:需要 HTTPS 网站,HTTP 会自动退用静音音频', '· 批量下载:未加载的章节会依次抓取,每章间隔 0.3~0.6 秒', '· 云备份:依赖 TextDB 免费服务,可能不稳定', ].join('\n'); alert(text); } function showStatus() { const recent = loadRecentSessions(); const purifyCount = loadPurifyList().length; const titlePatternCount = loadActiveTitlePatterns().length; const themeNames = { light: '浅色', sepia: '羊皮纸', dark: '暗黑', green: '豆沙绿', wood: '暖木色', blue: '静谧蓝', paper: '纸白色' }; const lines = []; const bookNameShow = filterBookName(store.bookName) || '(未识别)'; lines.push(`书名:${bookNameShow}`); lines.push(`书ID:${store.bookId || '(未识别)'}`); lines.push(`已加载:${store.chapters.filter(c => c && c.content).length} 章`); lines.push(`目录缓存:${store.tocList.length} 条${store.tocUrl ? '(' + store.tocUrl + ')' : ''}`); lines.push(`净化规则:${purifyCount} 条`); lines.push(`标题格式:${titlePatternCount} 条启用`); lines.push(`云备份 Key:${getCloudKey() || '(未设置)'}`); lines.push(`完结标记:${store.finished ? '是' : '否'}`); lines.push(`当前模式:${nativeMode.active ? '原网站模式' : (readerOpen ? '脚本阅读器' : '普通页面')}`); lines.push(`翻页布局:${settings.tapVertical ? '上下' : '左右'}`); lines.push(`自动翻页:${settings.autoPageEnabled ? '开(每 ' + settings.autoPageInterval + ' 秒)' : '关'}`); lines.push(`屏幕常亮:${wakeLock ? 'Wake Lock 已激活' : (wakeLockWanted ? '申请中/失败' : '关')}`); lines.push(`当前主题:${themeNames[settings.theme] || settings.theme}`); if (currentSessionId) lines.push(`当前会话 id:${currentSessionId}`); if (currentIndex >= 0) lines.push(`当前:第 ${currentIndex + 1} 条`); lines.push(`状态:${store.fetching ? '全本抓取中' : (store.finished ? '已完结' : '边读边下')}`); if (recent.length) { lines.push(''); lines.push(`最近阅读记录(${recent.length}/${MAX_RECENT}):`); recent.forEach((s, i) => { const when = new Date(s.time || 0).toLocaleString(); const cur = s.id === currentSessionId ? ' ←当前' : ''; const prog = makeProgressLabel(s); lines.push(` ${i + 1}. ${prog}${cur}`); lines.push(` ${when}`); }); } alert(lines.join('\n')); } // ==================== 启动 ==================== buildReader(); updateMenu(); maybeRestoreNativeMode(); console.log('[小说阅读器 v7.10.3] 已加载。标点自动通配中英文。'); if (nativeMode.active) console.log('[原生模式] 当前处于原网站模式'); })();