I am making UWP applications and I use WebView for displaying webpage content. The content is not mine so I would like to block the annoying video ads. I am using the function below to put css that hides banners. How to approach this task? Should I filter every HTTP request and if it meets some regex to stop the request? Or should I block the external javascripts that execute the ads? There are topics about this for Android WebView, but I couldn't make it work on UWP.
private async void InvokeScript()
{
string functionString = "let link = document.createElement('link'); link.rel =
'stylesheet'; link.type = 'text/css'; link.href = 'ms-appx-web:///MyCss.css';
document.getElementsByTagName('head')[0].appendChild(link);";
await webView.InvokeScriptAsync("eval", new string[] { functionString
});
}
I found a great solution from the Microsoft forum. For UWP WebView FrameNavigationStarting does the job!
webView.FrameNavigationStarting += webView_FrameNavigationStarting;
private void webView_FrameNavigationStarting(object sender, WebViewNavigationStartingEventArgs args)
{
// Cancel navigation if URL is not allowed. (Implemetation of IsAllowedUri not shown.)
if (!IsAllowedUri(args.Uri))
args.Cancel = true;
}