是否可以在WebView中显示的网页上获取信息?
答案 0 :(得分:4)
使用WebView
自定义渲染器(https://developer.xamarin.com/guides/cross-platform/xamarin-forms/custom-renderer/):
public class TitleWebView : Xamarin.Forms.WebView
{
public static readonly BindableProperty PageTitleProperty = BindableProperty.Create<TitleWebView, string>(v => v.PageTitle, null, BindingMode.OneWayToSource);
public string PageTitle
{
get { return (string)GetValue(PageTitleProperty); }
set { SetValue (PageTitleProperty, value); }
}
}
Android渲染器:
public class TitleWebViewRenderer : WebViewRenderer
{
protected override void OnElementChanged(ElementChangedEventArgs<Xamarin.Forms.WebView> e)
{
base.OnElementChanged(e);
if (e.OldElement == null)
{
Control.SetWebViewClient(new TitleWebViewClient(this));
}
}
internal class TitleWebViewClient : WebViewClient
{
readonly TitleWebViewRenderer titleWebViewRenderer;
internal TitleWebViewClient(TitleWebViewRenderer titleWebViewRenderer)
{
this.titleWebViewRenderer = titleWebViewRenderer;
}
public override void OnPageFinished(Android.Webkit.WebView view, string url)
{
base.OnPageFinished(view, url);
((IElementController) titleWebViewRenderer.Element).SetValueFromRenderer(TitleWebView.PageTitleProperty, view.Title);
}
}
iOS渲染器:
public class TitleWebViewRenderer : WebViewRenderer
{
public TitleWebViewRenderer()
{
this.LoadFinished += (object sender, EventArgs e) => {
var titleWebView = (TitleWebView)Element;
((IElementController)Element).SetValueFromRenderer(TitleWebView.PageTitleProperty,
EvaluateJavascript("document.title"));
};
}
}
答案 1 :(得分:0)
Daniel Luberda 的TitleWebView
类解决方案,已针对Xamarin 4.2进行了修复:
public class TitleWebView : WebView
{
public static readonly BindableProperty PageTitleProperty = BindableProperty.Create(
propertyName: "PageTitle",
defaultValue: string.Empty,
returnType: typeof(string),
declaringType: typeof(string),
defaultBindingMode: BindingMode.OneWayToSource);
public string PageTitle
{
get => (string) GetValue(PageTitleProperty);
set => SetValue(PageTitleProperty, value);
}
}