Taher El-hares
Taher El-hares

Reputation: 111

How to get the title of the webpage that the webview is currently holding?

I am trying to get the title of my webview, so I can store it in my database as a string. But I can't find a way to do so.

I tried to use mwebview.Title, but it's giving me the same result as the URL sometimes.

Upvotes: 2

Views: 1303

Answers (1)

Robert Bruce
Robert Bruce

Reputation: 1088

Here's a full example I put together using the OnPageFinished override in a custom WebViewClient.

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>

Upvotes: 1

Related Questions