☰

nhentai Scroll Feature

Adds scrolling to read feature on nhentai and a fallback load button (Might need to reload the page to get it initially working)

Dovrai installare un'estensione come Tampermonkey, Greasemonkey o Violentmonkey per installare questo script.

Dovrai installare un'estensione come Tampermonkey o Violentmonkey per installare questo script.

Dovrai installare un'estensione come Tampermonkey o Violentmonkey per installare questo script.

Dovrai installare un'estensione come Tampermonkey o Userscripts per installare questo script.

Dovrai installare un'estensione come ad esempio Tampermonkey per installare questo script.

Dovrai installare un gestore di script utente per installare questo script.

(Ho già un gestore di script utente, lasciamelo installare!)

Dovrai installare un'estensione come ad esempio Stylus per installare questo stile.

Dovrai installare un'estensione come ad esempio Stylus per installare questo stile.

Dovrai installare un'estensione come ad esempio Stylus per installare questo stile.

Dovrai installare un'estensione per la gestione degli stili utente per installare questo stile.

Dovrai installare un'estensione per la gestione degli stili utente per installare questo stile.

Dovrai installare un'estensione per la gestione degli stili utente per installare questo stile.

(Ho già un gestore di stile utente, lasciamelo installare!)

// ==UserScript==
// @name         nhentai Scroll Feature
// @namespace    http://tampermonkey.net/
// @version      1.0
// @description  Adds scrolling to read feature on nhentai and a fallback load button (Might need to reload the page to get it initially working)
// @match        *://nhentai.net/g/*/*/
// @match        *://nhentai.xxx/g/*/*/
// @match        *://nhentai.to/g/*/*/
// @match        *://nhentai.website/g/*/*/
// @match        *://nhentai.moe/g/*/*/
// @match        *://nhentai.ink/g/*/*/
// @match        *://nhentai.rocks/g/*/*/
// @match        *://*.nhentai.net/g/*/*/
// @match        *://*.nhentai.xxx/g/*/*/
// @match        *://*.nhentai.to/g/*/*/
// @match        *://*.nhentai.website/g/*/*/
// @match        *://*.nhentai.moe/g/*/*/
// @match        *://*.nhentai.ink/g/*/*/
// @match        *://*.nhentai.rocks/g/*/*/
// @grant        GM_xmlhttpRequest
// @run-at       document-end
// @license      MIT
// ==/UserScript==

(() => {
    'use strict';

    const match = location.pathname.match(/\/g\/(\d+)\/(\d+)\/?$/);
    if (!match) return;

    const galleryId = match[1];
    let renderedPage = Number(match[2]);
    let nextPage = renderedPage + 1;
    let inFlight = 0;
    let appending = false;
    let reachedEnd = false;
    let hasError = false;

    const PRELOAD_AHEAD = 2;
    const ready = new Map();
    const failedPages = new Set();
    const parser = new DOMParser();

    let box = null;
    let btn = null;

    const getUI = () => {
        const reader = document.querySelector('#image-container');
        const parent = reader || document.body;
        if (!parent) return null;

        if (!box) {
            box = document.createElement('div');
            box.style.width = '100%';
        }
        if (box.parentElement !== parent) {
            parent.appendChild(box);
        }

        if (!btn) {
            btn = document.createElement('button');
            btn.type = 'button';
            btn.textContent = 'Load More Pages';
            btn.style.cssText = 'display:none;margin:18px auto 28px;padding:12px 22px;font-size:15px;font-weight:600;color:#fff;background:#d9385a;border:none;border-radius:8px;cursor:pointer;';
            btn.addEventListener('click', () => {
                if (reachedEnd) return;
                hasError = false;
                btn.disabled = true;
                btn.textContent = 'Loading...';
                btn.style.display = 'block';
                for (const p of failedPages) {
                    fetchPage(p);
                }
                failedPages.clear();
                pump();
                updateBtn();
            });
        }
        if (btn.parentElement !== parent) {
            parent.appendChild(btn);
        }

        return { box, btn };
    };

    const updateBtn = () => {
        const ui = getUI();
        if (!ui) return;
        if (reachedEnd) {
            ui.btn.style.display = 'none';
            return;
        }
        if (inFlight > 0 || appending) {
            ui.btn.disabled = true;
            ui.btn.textContent = 'Loading...';
            ui.btn.style.display = hasError ? 'block' : 'none';
            return;
        }
        const nearBottom = window.innerHeight + window.scrollY >= document.documentElement.scrollHeight - 1200;
        if (hasError || (nearBottom && !ready.has(renderedPage + 1))) {
            ui.btn.disabled = false;
            ui.btn.textContent = 'Load More Pages';
            ui.btn.style.display = 'block';
        } else {
            ui.btn.style.display = 'none';
        }
    };

    const getSrc = (img) => {
        const raw = img.getAttribute('data-src') || img.getAttribute('data-cfsrc') || img.getAttribute('src');
        if (!raw) return '';
        try {
            return new URL(raw, location.origin).href;
        } catch {
            return '';
        }
    };

    const flush = () => {
        if (appending) return;
        const target = renderedPage + 1;
        const item = ready.get(target);
        if (!item) {
            updateBtn();
            return;
        }

        const ui = getUI();
        if (!ui) return;

        appending = true;
        ready.delete(target);

        const img = document.createElement('img');
        img.src = item.src;
        if (item.cls) img.className = item.cls;
        img.loading = 'eager';
        img.decoding = 'async';
        img.style.cssText = 'max-width:100%;height:auto;display:block;margin:10px auto;';

        const done = () => {
            renderedPage = target;
            appending = false;
            hasError = false;
            flush();
            pump();
            updateBtn();
        };

        img.onload = done;
        img.onerror = () => {
            appending = false;
            hasError = true;
            failedPages.add(target);
            updateBtn();
        };

        ui.box.appendChild(img);
    };

    const requestHtml = (url) => new Promise((resolve, reject) => {
        fetch(url, { credentials: 'include' })
            .then((r) => r.text().then((responseText) => resolve({ status: r.status, responseText })))
            .catch(() => {
                if (typeof GM_xmlhttpRequest !== 'function') {
                    reject(new Error('Request failed'));
                    return;
                }
                GM_xmlhttpRequest({
                    method: 'GET',
                    url,
                    timeout: 10000,
                    onload: (res) => resolve({ status: res.status, responseText: res.responseText || '' }),
                    onerror: reject,
                    ontimeout: reject
                });
            });
    });

    const fetchPage = async (pageNum) => {
        if (reachedEnd) return;
        inFlight++;
        updateBtn();

        try {
            const res = await requestHtml(`${location.origin}/g/${galleryId}/${pageNum}/`);
            inFlight--;

            if (res.status === 404) {
                reachedEnd = true;
                updateBtn();
                return;
            }
            if (res.status < 200 || res.status >= 300) {
                hasError = true;
                failedPages.add(pageNum);
                updateBtn();
                return;
            }

            const doc = parser.parseFromString(res.responseText, 'text/html');
            const img = doc.querySelector('#image-container img');
            const src = img && getSrc(img);
            if (!src) {
                hasError = true;
                failedPages.add(pageNum);
                updateBtn();
                return;
            }

            ready.set(pageNum, { src, cls: img.className });
            flush();
            pump();
            updateBtn();
        } catch {
            inFlight--;
            hasError = true;
            failedPages.add(pageNum);
            updateBtn();
        }
    };

    const pump = () => {
        if (reachedEnd) return;
        const maxAhead = renderedPage + PRELOAD_AHEAD;
        while (inFlight < PRELOAD_AHEAD && nextPage <= maxAhead) {
            if (!ready.has(nextPage) && !failedPages.has(nextPage)) {
                fetchPage(nextPage);
            }
            nextPage++;
        }
    };

    let rafId = 0;
    const onScroll = () => {
        if (rafId) return;
        rafId = requestAnimationFrame(() => {
            rafId = 0;
            flush();
            if (window.innerHeight + window.scrollY >= document.documentElement.scrollHeight - 1000) {
                pump();
            }
            updateBtn();
        });
    };

    window.addEventListener('scroll', onScroll, { passive: true });
    getUI();
    pump();
    updateBtn();
})();