2

My Xamarin Form WebView loads an external webpage like this,

<WebView VerticalOptions="FillAndExpand" HorizontalOptions="FillAndExpand" Source="<SOME_URL_HERE>" />

I need to hide the web page's menu injecting JavaScript or CSS. I also need to hide some unnecessary elements of a web page while it is loading through the app.

What is the best way to achieve this requirement? If there is any other way than JavaScript or CSS, that is also acceptable.

1 Answer 1

3

The WebView provides an EvaluateJavaScriptAsync method (see here), that you can use to execute JS.

You could for example subscribe to the Navigated event (see here)

<WebView VerticalOptions="FillAndExpand" HorizontalOptions="FillAndExpand" Source="<SOME_URL_HERE>" Navigated="WebViewOnNavigated" />

and when the WebView has navigated to, you can execute your JS from code behind

public async void WebViewOnNavigated(object sender, WebNavigatedEventArgs args)
{
    var webView = sender as WebView; // ommitting the null check, since nobody else will call this method
    await webView.EvaluateJavaScriptAsync("<Your JS goes here>");
}
Sign up to request clarification or add additional context in comments.

2 Comments

Simple JS such as alert are working but hiding elements etc not working. even this code is not working var webView = sender as WebView; var js = "document.getElementsByClassName('header_top').remove();"; await webView.EvaluateJavaScriptAsync(js);
@A.M.Roomi getElementsByClassName "Returns an array-like object of all child elements" (see here) - To remove the header you'll have to access a single element of that collection: document.getElementsByClassName('header_top')[0].remove(); (I have elided a check whether the element really exists.)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.