Search code examples
javascriptscrolldiscordtampermonkeywebautomation

How do I scroll to the bottom of the page using tampermonkey?


I'm trying to create a simple tampermonkey script to scroll to the very bottom of the page in discord after switching the channel, The script is supposed to wait for 5 seconds then scroll to the bottom of the channel so I could see the recent messages

the code currently does nothing, what I want it to do is scroll to the very bottom of the page

here's the code I've tried

(function() {
    'use strict';

    function scrollToBottom() {
        const scroller = document.querySelector('div[class*="scrollerContent-"]');
        if (scroller) {
            scroller.scrollTop = scroller.scrollHeight;
        }
    }

    function setupURLChangeObserver() {
        window.addEventListener('popstate', () => {
            setTimeout(scrollToBottom, 500);  // Delay to allow content to load
        });
    }

    setupURLChangeObserver();
})();
(function() {
    'use strict';

    function simulateMouseScroll() {
        const scroller = document.querySelector('div[class*="scrollerContent-"]');
        if (scroller) {
            for (let i = 0; i < 100; i++) {
                scroller.dispatchEvent(new WheelEvent('wheel', { deltaY: 100, bubbles: true }));
            }
        }
    }

    function setupURLChangeObserver() {
        window.addEventListener('popstate', () => {
            setTimeout(simulateMouseScroll, 500);  // Delay to allow content to load
        });
    }

    setupURLChangeObserver();
})();

I've also tried scroller.scrollTo(0, maxScrollTop);


Solution

  • Your selector (div[class*="scrollerContent-"]) is not correct, and popstate only fires in specific cases.

    Use the Navigation API instead, but Firefox does not support it yet. As an alternative you can use window.onurlchange (Tampermonkey only).

    For a cross browser/script-manager way to detect navigation, refer to my previous answer here.

    This should work for Chrome + Tampermonkey:

    window.navigation.addEventListener('navigatesuccess', () => {
        if (!window.location.pathname.startsWith('/channels/')) return;
    
        setTimeout( () => {
            const chat = document.querySelector('main[class^=chatContent] div[class^=scroller_]');
            const jump = document.querySelector('div[class^=jumpToPresentBar_] > button');
            jump && jump.click() || chat && chat.scrollTo(0, chat.scrollHeight)
        }, 100);
    });