Disable WebView Scrolling in Windows Store Apps

Introduction

WebView is a control that enables developers to host HTML content. In the WinRT framework, WebView still lacks some features compared to the web browser of WPF. The WebView class inherits from the FrameworkElement class, but many properties of the base class do not work in WebView.

Recently I was creating an app and I wanted to disable the horizontal and vertical scrolling of WebView. I tried the following code.

<WebView x:Name="webView" 
         Source="http://myawesomewebsite.com"
         ScrollViewer.VerticalScrollBarVisibility="Disabled"
         ScrollViewer.VerticalScrollMode="Disabled" />

But it didn't work. I was getting annoyed. I proceeded to use Bing and Google but didn't get any solution. WebView doesn't have its template also. Then I analyzed the control in detail. I finally understood that the scroll bars are due to HTML content, WebView itself doesn't have scroll bars. So I decided to go for a JavaScript solution. I applied some CSS properties in HTML content using JavaScript. It will display only the HTML content that is being displayed in the current viewport or say display area. WebView provides the InvokeScript method that executes the specified script function from the currently loaded HTML, with specific arguments. When WebView's LoadCompleted event occurs, I am invoking that JavaScript that disables the scrolling. Check out the entire code given below.

string DisableScrollingJs = @"function RemoveScrolling()
{
    var styleElement = document.createElement('style');
    var styleText = 'body, html { overflow: hidden; }'
    var headElements = document.getElementsByTagName('head');
    styleElement.type = 'text/css';
    
    if (headElements.length == 1)
    {
        headElements[0].appendChild(styleElement);
    }
    else if (document.head)
    {
        document.head.appendChild(styleElement);
    }

    if (styleElement.styleSheet)
    {
        styleElement.styleSheet.cssText = styleText;
    }
}";

void webView_LoadCompleted(object sender, NavigationEventArgs e)
{
    webView.InvokeScript("eval", new[] { DisableScrollingJs });
}

I hope this article will help you while developing a WebView-oriented app if you need to implement such a feature.

Summary

In this article, we learned about Disable WebView Scrolling in Windows Store Apps.


Similar Articles