Prevent The HTML Body from Scrolling using the WebView control – Universal Apps

Problem

The WebView control itself does not scroll when the HTML Body exceeds the size of the view.  Instead the HTML Document inside the control will scroll.  I decided to post a quick and simple resolution for this for Universal Apps (Windows Phone and Store 8.1 Apps).

Solution

The solution has actually nothing to do with how the WebView control works but with configuring the style of the HTML Body so that it does not scroll when the content ‘overflows’ the display!

First in your code define a string which is the JavaScript function you will execute and then call that function:

 private static string[] SetBodyOverFlowHiddenString = new string[] { @"// Define the function: function SetBodyOverFlowHidden() { document.body.style.overflow = 'hidden'; } // now call the function! SetBodyOverFlowHidden();" };

Now simply execute that script when the WebView ‘NavigationCompleted’ event fires:

 private async void theWebView_NavigationCompleted(WebView sender, WebViewNavigationCompletedEventArgs args) { await sender.InvokeScriptAsync("eval", SetBodyOverFlowHiddenString); } 

That is all there is to it!

More Information

This is not production ready code right?  You would need to ensure you place try-catch handlers in the script and in your C# code.  Also you should test the NavigationComplete arguments to ensure there was no error condition (like user cancelled) when the NavigationCompleted event was raised.

Enjoy and let know if this was useful to you and be sure to follow our team on Twitter @WSDevSol!