me is me
me is me

Reputation: 128

Get favicon from webview UWP

I have a question: how do I get the favicon of a page displayed in a webview in C# UWP? I want to store the icon to access it later. Is there any way of doing that?

Thank you.

Upvotes: 0

Views: 833

Answers (2)

me is me
me is me

Reputation: 128

I solved it. I did the following:

Uri icoURI = new Uri("https://www.google.com/s2/favicons?domain=" + WebPageView.Source);
currentTab.IconSource = new Microsoft.UI.Xaml.Controls.BitmapIconSource() { UriSource = icoURI, ShowAsMonochrome = false };

Upvotes: 0

Nico Zhu
Nico Zhu

Reputation: 32775

Get favicon from webview UWP

There is shortcut icon rel attribute in html that use to describe favicon. And you could use WebView InvokeScriptAsync to inject detected method into eval function and use window.external.notify pass favicon's href back.

For example

public MainPage()
{
    this.InitializeComponent();

    MyWebView.LoadCompleted += MyWebView_LoadCompleted;
}

private async void MyWebView_LoadCompleted(object sender, NavigationEventArgs e)
{
     string functionString = @"var nodeList = document.getElementsByTagName ('link');
for (var i = 0; i < nodeList.length; i++)
{
    if ((nodeList[i].getAttribute('rel') == 'icon') || (nodeList[i].getAttribute('rel') == 'shortcut icon'))
    {
        favicon = nodeList[i].getAttribute('href');
        window.external.notify(favicon); 
    }
}";

 await MyWebView.InvokeScriptAsync("eval", new string[] { functionString });

}

private void MyWebView_ScriptNotify(object sender, NotifyEventArgs e)
{
   var url = e.Value;
}

Please note

Allowed sites are specified in the Content URIs section of Package.appxmanifest and cannot contain domain wildcards and must be https .

enter image description here

And this is code sample that you could refer.

Upvotes: 2

Related Questions