☰

Multi-Platform Search Buttons for DLsite

Advanced search buttons for any DLsite work/announce page. Settings (gear). Supports RJ/BJ/VJ/RE/VE. F95Zone, Google, OtomiGames, Ryuugames + copy helpers. Survives Nuxt re-renders.

您需要先安裝使用者腳本管理器擴展,如 Tampermonkey、Greasemonkey 或 Violentmonkey 之後才能安裝該腳本。

您需要先安裝使用者腳本管理器擴充功能,如 Tampermonkey 或 Violentmonkey 後才能安裝該腳本。

您需要先安裝使用者腳本管理器擴充功能,如 Tampermonkey或 Violentmonkey 後才能安裝該腳本。

您需要先安裝使用者腳本管理器擴充功能,如 Tampermonkey或 Userscripts 後才能安裝該腳本。

你需要先安裝一款使用者腳本管理器擴展,比如 Tampermonkey,才能安裝此腳本

您需要先安裝使用者腳本管理器擴充功能後才能安裝該腳本。

(我已經安裝了使用者腳本管理器,讓我安裝!)

你需要先安裝一款使用者樣式管理器擴展,比如 Stylus,才能安裝此樣式

你需要先安裝一款使用者樣式管理器擴展,比如 Stylus,才能安裝此樣式

你需要先安裝一款使用者樣式管理器擴展,比如 Stylus,才能安裝此樣式

你需要先安裝一款使用者樣式管理器擴展後才能安裝此樣式

你需要先安裝一款使用者樣式管理器擴展後才能安裝此樣式

你需要先安裝一款使用者樣式管理器擴展後才能安裝此樣式

(我已經安裝了使用者樣式管理器,讓我安裝!)

// ==UserScript==
// @name         Multi-Platform Search Buttons for DLsite
// @namespace    http://tampermonkey.net/
// @version      4.15.0
// @description  Advanced search buttons for any DLsite work/announce page. Settings (gear). Supports RJ/BJ/VJ/RE/VE. F95Zone, Google, OtomiGames, Ryuugames + copy helpers. Survives Nuxt re-renders.
// @author       FunkyJustin
// @match        https://www.dlsite.com/*/work/=/product_id/*
// @match        https://www.dlsite.com/*/announce/=/product_id/*
// @match        https://www.dlsite.com/*-touch/work/=/product_id/*
// @match        https://www.dlsite.com/*-touch/announce/=/product_id/*
// @match        https://f95zone.to/*
// @grant        GM_openInTab
// @grant        GM_getValue
// @grant        GM_setValue
// @license      MIT
// ==/UserScript==
/*
Update History:
- v4.15.0: Hardened against Nuxt/Vue re-renders that were wiping the UI on some works (e.g. RJ01726029). Now targets stable .c-productTitleBoxPc container, continuously re-injects if removed, keeps a persistent floating fallback button, longer observer/poll. Total lines ~480.
- v4.14.0: MAJOR FIX for new DLsite Nuxt layout. Replaced obsolete .base_title_br. Floating fallback. Improved extraction & observer.
- v4.13.0: CRITICAL FIX – corrected GM_openInTab call (invalid tagged-template). Expanded @match.
- v4.12.1: Fixed product ID extraction to support VJ/BJ/RE/VE.
*/
(function () {
    'use strict';

    const VERSION = '4.15.0';
    const LOG  = (...a) => console.log('[DLsite Search Buttons]', ...a);
    const WARN = (...a) => console.warn('[DLsite Search Buttons]', ...a);

    // ==================== F95Zone Handler ====================
    if (window.location.href.includes('f95zone.to')) {
        const urlParams = new URLSearchParams(window.location.search);
        const query = urlParams.get('query');
        if (query) {
            const form = document.createElement('form');
            form.method = 'POST';
            form.action = 'https://f95zone.to/search/search';
            form.style.display = 'none';
            const inputs = {
                'keywords': query,
                'order': 'relevance',
                '_xfToken': document.querySelector('input[name="_xfToken"]')?.value || ''
            };
            for (const [name, value] of Object.entries(inputs)) {
                const input = document.createElement('input');
                input.type = 'hidden';
                input.name = name;
                input.value = value;
                form.appendChild(input);
            }
            document.body.appendChild(form);
            fetch(form.action, {
                method: 'POST',
                body: new FormData(form),
                redirect: 'follow'
            })
            .then(response => {
                const match = response.url.match(/\/search\/(\d+)\//);
                window.location.href = match
                    ? `https://f95zone.to/search/${match[1]}/?q=${encodeURIComponent(query)}&o=relevance`
                    : `https://f95zone.to/search/?q=${encodeURIComponent(query)}&o=relevance`;
            })
            .catch(() => {
                window.location.href = `https://f95zone.to/search/?q=${encodeURIComponent(query)}&o=relevance`;
            })
            .finally(() => {
                if (form.parentNode) document.body.removeChild(form);
            });
        }
        return;
    }

    // ==================== SETTINGS ====================
    const SETTINGS = {
        get defaultOpen() { return GM_getValue('dropdown_default_open', true); },
        set defaultOpen(v) { GM_setValue('dropdown_default_open', v); }
    };

    // ==================== CONFIG ====================
    const CONFIG = {
        groups: [
            {
                name: 'F95Zone',
                buttons: [
                    { text: 'Search on F95Zone', url: d => `https://f95zone.to/sam/latest_alpha/#/cat=games/page=1/search=${encodeURIComponent(d.gameTitle)}`, icon: 'f95zone' },
                    { text: 'Search on F95Zone Forums', query: d => d.gameTitle, isF95Forum: true, icon: 'f95zone' },
                    { text: 'Search Product ID on F95Zone Forums', query: d => d.productId, isF95Forum: true, icon: 'f95zone' },
                ]
            },
            {
                name: 'Utilities',
                buttons: [
                    { text: 'Copy Product ID', action: 'copyPID' },
                    { text: 'Search Product ID on Google', url: d => `https://www.google.com/search?q="${d.productId}"`, icon: 'google' },
                    { text: 'Search Title on Google', url: d => `https://www.google.com/search?q=${encodeURIComponent(d.gameTitle)}`, icon: 'google' },
                    { text: 'Copy Title', action: 'copyTitle' },
                ]
            },
            {
                name: 'OtomiGames',
                buttons: [
                    { text: 'Search on OtomiGames', url: d => `https://otomi-games.com/?s=${encodeURIComponent(d.gameTitle)}`, icon: 'otomi' },
                    { text: 'Search Product ID on OtomiGames', url: d => `https://otomi-games.com/?s=${encodeURIComponent(d.productId)}`, icon: 'otomi' },
                ]
            },
            {
                name: 'Ryuugames',
                buttons: [
                    { text: 'Search on Ryuugames', url: d => `https://www.ryuugames.com/?s=${encodeURIComponent(d.gameTitle)}`, icon: 'ryuugames' },
                    { text: 'Search Product ID on Ryuugames', url: d => `https://www.ryuugames.com/?s=${encodeURIComponent(d.productId)}`, icon: 'ryuugames' },
                ]
            }
        ]
    };

    // ==================== CSS ====================
    if (!document.getElementById('dlsite-search-buttons-style')) {
        const style = document.createElement('style');
        style.id = 'dlsite-search-buttons-style';
        style.textContent = `
            :root {
                --dsb-bg-start: #D6BCFA;
                --dsb-bg-end: #FBB6CE;
                --dsb-border: #B794F4;
                --dsb-pink: #E91E63;
            }
            .dsb-btn {
                display: inline-flex; align-items: center;
                padding: 5px 9px; margin: 3px;
                background: linear-gradient(45deg, var(--dsb-bg-start), var(--dsb-bg-end));
                color: #800080 !important; text-decoration: none;
                border-radius: 12px; border: 1px solid var(--dsb-border);
                box-shadow: 0 2px 4px rgba(0,0,0,.1);
                font-family: Arial, sans-serif; font-size: 14.5px; font-weight: bold;
                transition: all .2s; cursor: pointer; white-space: nowrap;
            }
            .dsb-btn:hover { box-shadow: 0 4px 8px rgba(0,0,0,.15); opacity: .95; }
            .dsb-btn img { width: 18px; height: 18px; margin-right: 6px; }
            .dsb-dropdown {
                max-width: 680px; margin: 12px 0 20px 0;
                position: relative; z-index: 40;
            }
            .dsb-header { display: flex; align-items: center; gap: 8px; }
            .dsb-toggle {
                display: flex; align-items: center; flex: 1;
                padding: 6px 12px; background: var(--dsb-pink); color: #fff;
                border: none; border-radius: 12px;
                font-family: Arial, sans-serif; font-size: 14px; font-weight: bold;
                cursor: pointer;
            }
            .dsb-toggle::after { content: ' ▼'; margin-left: 8px; transition: transform .3s; }
            .dsb-toggle.collapsed::after { transform: rotate(180deg); }
            .dsb-gear {
                background: none; border: none; font-size: 18px;
                cursor: pointer; padding: 6px; border-radius: 50%; color: #fff; opacity: .9;
            }
            .dsb-gear:hover { background: rgba(255,255,255,.25); }
            .dsb-content {
                display: block; background: #f9f9f9; border-radius: 8px;
                box-shadow: 0 2px 4px rgba(0,0,0,.1); padding: 12px; margin-top: 6px;
            }
            .dsb-content.hidden { display: none; }
            .dsb-version {
                position: absolute; bottom: 6px; right: 12px;
                font-size: 11px; color: #888; pointer-events: none;
            }
            .dsb-group { margin-bottom: 12px; }
            .dsb-group-label {
                font-family: Arial, sans-serif; font-size: 14px; font-weight: bold;
                color: #333; margin-bottom: 6px;
            }
            .dsb-grid {
                display: grid;
                grid-template-columns: repeat(auto-fit, minmax(240px, 1fr));
                gap: 6px;
            }
            .dsb-circle-wrap {
                display: flex; align-items: center; margin-top: 6px;
                gap: 6px; flex-wrap: wrap;
            }
            /* Floating launcher (always available) */
            .dsb-float-launcher {
                position: fixed; bottom: 20px; right: 20px; z-index: 99980;
                width: 52px; height: 52px; border-radius: 50%;
                background: var(--dsb-pink); color: #fff; border: none;
                font-size: 22px; cursor: pointer;
                box-shadow: 0 4px 16px rgba(233,30,99,.45);
                display: flex; align-items: center; justify-content: center;
            }
            .dsb-float-launcher:hover { transform: scale(1.08); }
            .dsb-float-panel {
                position: fixed; bottom: 80px; right: 20px; z-index: 99981;
                width: 340px; max-height: 70vh; overflow-y: auto;
                background: #fff; border-radius: 12px;
                box-shadow: 0 8px 32px rgba(0,0,0,.28); padding: 14px;
                font-family: Arial, sans-serif; display: none;
            }
            .dsb-float-panel.open { display: block; }
            .dsb-float-panel .dsb-float-title {
                display: flex; justify-content: space-between; align-items: center;
                font-weight: bold; color: var(--dsb-pink); margin-bottom: 10px;
            }
            .dsb-float-panel .dsb-float-close {
                background: none; border: none; font-size: 20px; cursor: pointer; line-height: 1;
            }
            /* Settings modal */
            .dsb-modal {
                position: fixed; inset: 0; background: rgba(0,0,0,.65);
                display: none; align-items: center; justify-content: center; z-index: 99999;
            }
            .dsb-modal-inner {
                background: #fff; padding: 24px; border-radius: 12px; width: 340px;
                box-shadow: 0 8px 30px rgba(0,0,0,.3);
            }
            .dsb-modal-inner h3 { margin: 0 0 16px; color: #333; }
            .dsb-modal-inner label { display: block; margin: 14px 0; font-size: 15px; cursor: pointer; }
            .dsb-modal-btns { margin-top: 24px; text-align: right; }
            .dsb-modal-btns button {
                padding: 8px 18px; margin-left: 10px; border: none;
                border-radius: 6px; cursor: pointer; font-size: 14px;
            }
            .dsb-modal-btns .cancel { background: #ddd; color: #333; }
            .dsb-modal-btns .save { background: var(--dsb-pink); color: #fff; }
        `;
        document.head.appendChild(style);
    }

    const icons = {
        f95zone: 'https://f95zone.to/favicon.ico',
        ryuugames: 'https://www.ryuugames.com/wp-content/uploads/2020/05/cropped-ryuugames_logo-1-32x32.png',
        otomi: 'https://otomi-games.com/favicon.ico',
        google: 'https://www.google.com/favicon.ico'
    };

    // ==================== HELPERS ====================
    function createButton(cfg, data) {
        let el;
        if (cfg.isF95Forum) {
            el = document.createElement('button');
            el.type = 'button';
            el.addEventListener('mousedown', e => {
                if (e.button === 0 || e.button === 1) {
                    e.preventDefault();
                    GM_openInTab(
                        `https://f95zone.to/?query=${encodeURIComponent(cfg.query(data))}`,
                        { active: e.button === 0, setParent: true }
                    );
                }
            });
        } else {
            el = document.createElement('a');
            el.href = cfg.url ? cfg.url(data) : '#';
            el.target = '_blank';
            el.rel = 'noopener noreferrer';
        }
        el.className = 'dsb-btn';
        el.title = cfg.text;
        if (cfg.icon && icons[cfg.icon]) {
            const img = document.createElement('img');
            img.src = icons[cfg.icon];
            img.alt = '';
            el.appendChild(img);
        }
        el.appendChild(document.createTextNode(cfg.text));
        return el;
    }

    function attachCopy(btn, text) {
        btn.addEventListener('click', e => {
            e.preventDefault();
            const flash = () => {
                const o = btn.textContent;
                btn.textContent = '✓ Copied!';
                setTimeout(() => { btn.textContent = o; }, 1800);
            };
            if (navigator.clipboard?.writeText) {
                navigator.clipboard.writeText(text).then(flash).catch(() => {
                    const ta = document.createElement('textarea');
                    ta.value = text; document.body.appendChild(ta);
                    ta.select(); document.execCommand('copy');
                    document.body.removeChild(ta); flash();
                });
            } else {
                const ta = document.createElement('textarea');
                ta.value = text; document.body.appendChild(ta);
                ta.select(); document.execCommand('copy');
                document.body.removeChild(ta); flash();
            }
        });
    }

    function createGroup(group, data) {
        const wrap = document.createElement('div');
        wrap.className = 'dsb-group';
        if (group.name) {
            const lab = document.createElement('div');
            lab.className = 'dsb-group-label';
            lab.textContent = group.name;
            wrap.appendChild(lab);
        }
        const grid = document.createElement('div');
        grid.className = 'dsb-grid';
        group.buttons.forEach(cfg => {
            let btn;
            if (cfg.action === 'copyPID') {
                btn = createButton({ text: cfg.text }, data);
                attachCopy(btn, data.productId);
            } else if (cfg.action === 'copyTitle') {
                btn = createButton({ text: cfg.text }, data);
                attachCopy(btn, data.gameTitle);
            } else {
                btn = createButton(cfg, data);
            }
            grid.appendChild(btn);
        });
        wrap.appendChild(grid);
        return wrap;
    }

    function getProductData() {
        const titleEl = document.querySelector('h1#work_name') ||
                        document.querySelector('h1.headline__title') ||
                        document.querySelector('h1');
        let gameTitle = titleEl ? (titleEl.textContent || '').trim() : '';
        gameTitle = gameTitle.replace(/\s*\[.*?\]\s*$/, '').trim();

        const circleSelectors = [
            'a.c-productInfo__makerName',
            '.c-productInfo__maker a',
            'span.maker_name a',
            'a[href*="maker_id"]',
            '.breadcrumb__label[href*="maker_id"]'
        ];
        let circleName = '', circleLink = null;
        for (const sel of circleSelectors) {
            const el = document.querySelector(sel);
            if (el && el.textContent.trim()) {
                circleName = el.textContent.trim();
                circleLink = el;
                break;
            }
        }

        let productId = '';
        const m = location.href.match(/product_id\/([A-Z]{2}\d+)/i) ||
                  location.pathname.match(/\/([A-Z]{2}\d+)(?:\.html)?/i);
        if (m) productId = m[1].toUpperCase();
        if (!productId) {
            const d = document.querySelector('[data-product_id]');
            if (d) productId = d.getAttribute('data-product_id').toUpperCase();
        }

        return { gameTitle, circleName, productId, circleLink };
    }

    // ==================== SETTINGS ====================
    function showSettings() {
        let modal = document.getElementById('dsb-settings-modal');
        if (!modal) {
            modal = document.createElement('div');
            modal.id = 'dsb-settings-modal';
            modal.className = 'dsb-modal';
            modal.innerHTML = `
                <div class="dsb-modal-inner">
                    <h3>⚙️ Script Settings <small style="font-weight:normal;color:#888">v${VERSION}</small></h3>
                    <label><input type="checkbox" id="dsb-default-open"> Open "Search Options" dropdown by default</label>
                    <div class="dsb-modal-btns">
                        <button class="cancel" id="dsb-cancel">Cancel</button>
                        <button class="save" id="dsb-save">Save & Reload</button>
                    </div>
                </div>`;
            document.body.appendChild(modal);
            document.getElementById('dsb-cancel').onclick = () => modal.style.display = 'none';
            document.getElementById('dsb-save').onclick = () => {
                SETTINGS.defaultOpen = document.getElementById('dsb-default-open').checked;
                modal.style.display = 'none';
                location.reload();
            };
            modal.addEventListener('click', e => { if (e.target === modal) modal.style.display = 'none'; });
        }
        document.getElementById('dsb-default-open').checked = SETTINGS.defaultOpen;
        modal.style.display = 'flex';
    }

    // ==================== BUILD UI ====================
    function buildDropdown(data) {
        const box = document.createElement('div');
        box.className = 'dsb-dropdown';
        box.dataset.dsbMain = '1';

        const header = document.createElement('div');
        header.className = 'dsb-header';

        const toggle = document.createElement('button');
        toggle.type = 'button';
        toggle.className = 'dsb-toggle';
        toggle.textContent = 'Search Options';

        const gear = document.createElement('button');
        gear.type = 'button';
        gear.className = 'dsb-gear';
        gear.innerHTML = '⚙️';
        gear.title = 'Settings';
        gear.onclick = e => { e.stopImmediatePropagation(); showSettings(); };

        header.append(toggle, gear);

        const content = document.createElement('div');
        content.className = 'dsb-content';
        if (!SETTINGS.defaultOpen) {
            content.classList.add('hidden');
            toggle.classList.add('collapsed');
        }
        toggle.onclick = () => {
            content.classList.toggle('hidden');
            toggle.classList.toggle('collapsed');
        };

        CONFIG.groups.forEach(g => content.appendChild(createGroup(g, data)));

        const ver = document.createElement('div');
        ver.className = 'dsb-version';
        ver.textContent = 'v' + VERSION;

        box.append(header, content, ver);
        return box;
    }

    function ensureFloatingUI(data) {
        if (document.querySelector('.dsb-float-launcher')) return;

        const launcher = document.createElement('button');
        launcher.type = 'button';
        launcher.className = 'dsb-float-launcher';
        launcher.title = `Search Options v${VERSION}`;
        launcher.textContent = '🔍';
        launcher.dataset.dsbFloat = '1';

        const panel = document.createElement('div');
        panel.className = 'dsb-float-panel';
        panel.dataset.dsbFloat = '1';

        const title = document.createElement('div');
        title.className = 'dsb-float-title';
        title.innerHTML = `<span>Search Options <small>v${VERSION}</small></span>`;
        const close = document.createElement('button');
        close.type = 'button';
        close.className = 'dsb-float-close';
        close.textContent = '×';
        close.onclick = () => panel.classList.remove('open');
        title.appendChild(close);
        panel.appendChild(title);

        CONFIG.groups.forEach(g => panel.appendChild(createGroup(g, data)));

        launcher.onclick = () => panel.classList.toggle('open');

        document.body.appendChild(launcher);
        document.body.appendChild(panel);
        LOG('Floating launcher ready');
    }

    // ==================== INJECTION ====================
    function injectMain(data) {
        // Already present and still in the document?
        const existing = document.querySelector('.dsb-dropdown[data-dsb-main]');
        if (existing && document.body.contains(existing)) return true;

        // Remove orphaned node if Vue left a detached one
        if (existing) existing.remove();

        const candidates = [
            document.querySelector('.c-productTitleBoxPc'),   // most stable
            document.querySelector('.headline__row'),
            document.querySelector('.headline.headline_L'),
            document.querySelector('h1#work_name')?.closest('.headline'),
            document.querySelector('h1#work_name')?.parentElement,
        ].filter(Boolean);

        for (const target of candidates) {
            try {
                const dropdown = buildDropdown(data);
                if (target.nextSibling) {
                    target.parentNode.insertBefore(dropdown, target.nextSibling);
                } else {
                    target.parentNode.appendChild(dropdown);
                }
                LOG('Main UI injected after', target.className || target.tagName);
                return true;
            } catch (e) {
                WARN('Insert failed on', target, e);
            }
        }
        return false;
    }

    function injectCircle(data) {
        if (!data.circleName || !data.circleLink) return;
        if (document.querySelector('[data-dsb-circle]')) return;

        const wrapper = document.createElement('span');
        wrapper.className = 'dsb-circle-wrap';
        wrapper.dataset.dsbCircle = '1';

        const configs = [
            { text: 'Search Circle on F95Zone', url: d => `https://f95zone.to/sam/latest_alpha/#/cat=games/page=1/creator=${encodeURIComponent(d.circleName)}`, icon: 'f95zone' },
            { text: 'Search Circle on F95Zone Forums', query: d => d.circleName, isF95Forum: true, icon: 'f95zone' },
            { text: 'Search Circle on Ryuugames', url: d => `https://www.ryuugames.com/?s=${encodeURIComponent(d.circleName)}`, icon: 'ryuugames' },
            { text: 'Search Circle on OtomiGames', url: d => `https://otomi-games.com/?s=${encodeURIComponent(d.circleName)}`, icon: 'otomi' },
        ];
        configs.forEach(c => wrapper.appendChild(createButton(c, data)));

        const anchor = data.circleLink.closest('.c-productInfo__maker') ||
                       data.circleLink.closest('span.maker_name') ||
                       data.circleLink.parentNode;
        if (anchor?.parentNode) {
            anchor.parentNode.insertBefore(wrapper, anchor.nextSibling);
        }
    }

    function tryInject() {
        const data = getProductData();
        if (!data.productId || !data.gameTitle) {
            return false;
        }

        // Always ensure floating UI exists (survives any re-render)
        ensureFloatingUI(data);

        const ok = injectMain(data);
        injectCircle(data);
        return ok;
    }

    // ==================== RUN ====================
    if (!location.href.includes('dlsite.com')) return;

    let attempts = 0;
    const MAX = 60; // 30 s

    function tick() {
        attempts++;
        const success = tryInject();
        // Keep trying a few more times even after success so we can recover from Vue wipes
        if (attempts >= MAX) {
            LOG('Stopped after', attempts, 'attempts');
            return true; // stop
        }
        return false;
    }

    if (document.readyState === 'loading') {
        document.addEventListener('DOMContentLoaded', () => tick());
    } else {
        tick();
    }

    // MutationObserver – re-inject when Vue destroys our node
    const observer = new MutationObserver(() => {
        const mainGone = !document.querySelector('.dsb-dropdown[data-dsb-main]');
        const floatGone = !document.querySelector('.dsb-float-launcher');
        if (mainGone || floatGone) {
            tryInject();
        }
    });
    observer.observe(document.documentElement, { childList: true, subtree: true });

    // Polling backup
    const poll = setInterval(() => {
        if (tick()) {
            clearInterval(poll);
        }
    }, 500);

    // Hard stop after 35 s
    setTimeout(() => {
        clearInterval(poll);
        // Keep a lightweight observer forever so Vue SPA navigations still work
        LOG('Long-term observer active');
    }, 35000);

    LOG('v' + VERSION + ' loaded – watching…');
})();