如何获取webview当前持有的网页标题?

时间:2019-05-16 12:55:47

标签: c# xamarin xamarin.android visual-studio-2017

我正在尝试获取Web视图的标题,因此可以将其作为字符串存储在数据库中。但是我找不到办法。

我尝试使用mwebview.Title,但有时会得到与URL相同的结果。

1 个答案:

答案 0 :(得分:1)

这是一个完整的示例,我在自定义WebViewClient中使用OnPageFinished替代内容放在一起。

WebViewCustomActivity.cs

using System;
using Android.App;
using Android.OS;
using Android.Webkit;

namespace XamdroidMaster.Activities {

    [Activity(Label = "Custom WebViewClient", MainLauncher = true)]
    public class WebViewCustomActivity : Activity {

        protected override void OnCreate(Bundle savedInstanceState) {
            base.OnCreate(savedInstanceState);

            SetContentView(Resource.Layout.WebView);
            WebView wv = FindViewById<WebView>(Resource.Id.webviewMain);

            CustomWebViewClient customWebViewClient = new CustomWebViewClient();
            customWebViewClient.OnPageLoaded += CustomWebViewClient_OnPageLoaded;

            wv.SetWebViewClient(customWebViewClient);
            wv.LoadUrl("https://www.stackoverflow.com");
        }

        private void CustomWebViewClient_OnPageLoaded(object sender, string sTitle) {
            Android.Util.Log.Info("MyApp", $"OnPageLoaded Fired - Page Title = {sTitle}");
        }

    }

    public class CustomWebViewClient : WebViewClient {

        public event EventHandler<string> OnPageLoaded;

        public override void OnPageFinished(WebView view, string url) {
            OnPageLoaded?.Invoke(this, view.Title);
        }

    }

}

WebView.axml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/WebView"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="@android:color/transparent">
    <WebView
        android:id="@+id/webviewMain"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:background="#FFFFFF" />
</LinearLayout>