WebView is a control that enables developers to host HTML content. In the WinRT framework WebView still lacks some features compared to the WebBrowser of WPF. The WebView class inherits from the FrameworkElement class, but many properties of the base class does 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 its own 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 that 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 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.