Search code examples
webviewwindows-10windows-10-mobile

WebView SaveToString() Equivalent


I have been using SaveToString() method to get the source code of the page in WebBrowser Control. But since its been deprecated in Windows 10, Whats the equivalent for SaveToString() in WebView Control of Windows 10.


Solution

  • WebView allows us to invoke script, and we can dump the document.documentElement.outerHTML to do the same thing as SaveToString().

    The following shows a very simple sample for your test. Note that I didn't try to make a cool UI design and make all things formatted, but only try to show you the idea.

    In xaml:

        <StackPanel>
            <WebView x:Name="MyWebView" Source="http://www.bing.com" Height="200" 
                     DOMContentLoaded="MyWebView_DOMContentLoaded"/>
            <Button x:Name="ViewSourceBtn" Content="View Source" Click="ViewSourceBtn_Click"/>
            <RichTextBlock x:Name="SourceBlock" Height="300" >
            </RichTextBlock>
        </StackPanel>
    

    Code behind:

        bool contentloaded = false;
        private async void ViewSourceBtn_Click(object sender, RoutedEventArgs e)
        {
            if (contentloaded)
            {
                string html = await MyWebView.InvokeScriptAsync("eval", new string[] { "document.documentElement.outerHTML;" });
                var paragraph = new Paragraph();
                paragraph.Inlines.Add(new Run { Text = html });
                SourceBlock.Blocks.Clear();
                SourceBlock.Blocks.Add(paragraph);
            }
            else
            {
                string err = "Waiting for HTML content to load!";
                var paragraph = new Paragraph();
                paragraph.Inlines.Add(new Run { Text = err });
                SourceBlock.Blocks.Clear();
                SourceBlock.Blocks.Add(paragraph);
            }
        }
    
        private void MyWebView_DOMContentLoaded(WebView sender, WebViewDOMContentLoadedEventArgs args)
        {
            contentloaded = true;
        }
    

    Here is the result by clicking view source button: enter image description here