February 26, 2021

WebView2: How to hide scrollbars

Problem

When using the new Microsoft Edge WebView2 control, it often displays scroll bars and the control doesn't have any explicit property to hide the scroll bars.



Solution

You need to use custom Javascript at the NavigationCompleted event to hide the scrollbars. 

Simply add a new NavigationCompleted event handler for the WebView2 control and use the ExecuteScriptAsync method to run a Javascript that hides the scroll bars.

1
2
3
4
5
6
7
private void WebView2_NavigationCompleted(object sender, CoreWebView2NavigationCompletedEventArgs e)
{
    if (e.IsSuccess)
    {
        ((WebView2)sender).ExecuteScriptAsync("document.querySelector('body').style.overflow='hidden'");
    }
}

Note! Code above hides scrollbars AND disables scrolling. If you would like to hide scrollbars but retain scrolling (with touch for example), please use this code instead.

1
2
3
4
5
6
7
private void WebView2_NavigationCompleted(object sender, CoreWebView2NavigationCompletedEventArgs e)
{
    if (e.IsSuccess)
    {
        ((WebView2)sender).ExecuteScriptAsync("document.querySelector('body').style.overflow='scroll';var style=document.createElement('style');style.type='text/css';style.innerHTML='::-webkit-scrollbar{display:none}';document.getElementsByTagName('body')[0].appendChild(style)");
    }
}

No comments:

Post a Comment