Search code examples
javascriptcssgoogle-chrome-extensionscrollbarcontent-script

Hide/show scrollbar from chrome extension


I'm trying to hide\show scrollbars on pages via my Chrome Extension.

I hide it by inserting this CSS from background.js file:

::-webkit-scrollbar {
    display: none !important;
}

::-webkit-scrollbar-button {
    display: none !important;
}

and I try to show it again by inserting this CSS from background.js file:

::-webkit-scrollbar {
    display: block !important;
}

::-webkit-scrollbar-button {
    display: block !important;
}

Hiding works, but I'm unable to restore it afterwards. When I inspect the page through Chrome DevTools, it shows as if both of the inserted CSS are active at same time.

Is there any other way to do this? Important thing to note is that this should work on any page, so I'm able to remove and restore scrollbars from any page CSS is inserted to.

I'm open for any other way, JavaScript too.


Solution

  • I accomplished this through content-script. This code removes scrollbars and still allows you to scroll with mousewheel or keyboard buttons:

        var styleElement = document.createElement('style');
        styleElement.id = 'remove-scroll-style';
        styleElement.textContent =
            'html::-webkit-scrollbar{display:none !important}' +
            'body::-webkit-scrollbar{display:none !important}';
        document.getElementsByTagName('body')[0].appendChild(styleElement);
    

    And this code restores scrollbars:

    $('#remove-scroll-style').remove();