How to get document of WebView in WPF?

0

I'm using Microsoft Toolkit Web View to embed Microsoft Edge in my WPF C# application.

I can't find anyway to get document and innerHTML of webview and there's nothing in documentation.

Here's XAML :

<UserControl x:Class="webviewtest.MainControl"
             xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
             xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
             xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" 
             xmlns:d="http://schemas.microsoft.com/expression/blend/2008" 
             xmlns:webv="clr-namespace:Microsoft.Toolkit.Wpf.UI.Controls;assembly=Microsoft.Toolkit.Wpf.UI.Controls.WebView"
             xmlns:local="clr-namespace:webviewtest"
             mc:Ignorable="d" 
             Width="500" Height="500" >
    <Grid>
    <webv:WebView x:Name="webview_browser" Margin="0" IsJavaScriptEnabled="True" IsPrivateNetworkClientServerCapabilityEnabled="True"/>
    </Grid>
</UserControl>

And here's C# :

public partial class MainControl : UserControl
    {

        public MainControl()
        {
            InitializeComponent();
           
            webview_browser.Source = new Uri(@"http://google.com");
            
            ///// HOW TO GET webview_browser CONTENT AND HTML DOCUMENT 
           
        }
   
    }

I also tried :

string GETHTML = webview_browser.InvokeScript(@"document.innerHTML").ToString();

But I get this error :

System.AggregateException: 'One or more errors occurred.' Exception: Unknown name. (Exception from HRESULT: 0x80020006 (DISP_E_UNKNOWNNAME))

Thanks

c#
wpf
webview
microsoft-edge
asked on Stack Overflow Apr 11, 2019 by Dr.CSharp • edited Jun 20, 2020 by Community

1 Answer

1

Add this as a method to your MainControl class

async private void WebView_DOMContentLoaded(WebView sender, WebViewDOMContentLoadedEventArgs args)
    {
        string html = await webview.InvokeScriptAsync("eval", new string[] { "document.documentElement.outerHTML;" });
        _html = html; //A property of your class to store the value when the event is fired
    }

And change this:

<webv:WebView x:Name="webview_browser" Margin="0" IsJavaScriptEnabled="True" IsPrivateNetworkClientServerCapabilityEnabled="True"/>

to this:

<webv:WebView x:Name="webview_browser" Margin="0" IsJavaScriptEnabled="True" IsPrivateNetworkClientServerCapabilityEnabled="True" DOMContentLoaded="WebView_DOMContentLoaded"/>

to fetch the html document after the page is loaded.

answered on Stack Overflow Apr 11, 2019 by Rapture • edited Apr 11, 2019 by Rapture

User contributions licensed under CC BY-SA 3.0