首页 > 解决方案 > 如何获取 webview 当前持有的网页标题?

问题描述

我正在尝试获取我的 webview 的标题,所以我可以将它作为字符串存储在我的数据库中。但我找不到这样做的方法。

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

标签: c#xamarinxamarin.androidvisual-studio-2017

解决方案


这是我在自定义 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>

推荐阅读