我可以将JavaScript和CSS注入Xamarin Form WebView吗? [英] Can I inject JavaScript and CSS into Xamarin Form WebView?
问题描述
我的Xamarin Form WebView加载这样的外部网页,
My Xamarin Form WebView loads an external webpage like this,
<WebView VerticalOptions="FillAndExpand" HorizontalOptions="FillAndExpand" Source="<SOME_URL_HERE>" />
我需要隐藏注入JavaScript或CSS的网页菜单.在通过应用程序加载网页时,我还需要隐藏网页的一些不必要的元素.
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.
达到此要求的最佳方法是什么?如果有JavaScript或CSS以外的其他方式,那也是可以接受的.
What is the best way to achieve this requirement? If there is any other way than JavaScript or CSS, that is also acceptable.
推荐答案
WebView
提供了 EvaluateJavaScriptAsync
方法(请参见
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" />
,并且当 WebView
导航到后,您可以从后面的代码中执行JS
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>");
}
这篇关于我可以将JavaScript和CSS注入Xamarin Form WebView吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!