02、获取 WebView 控件中,加载的 HTML 网页内容

 


     在开发 app 的时候,WebView 是经常使用的控件。而且有时需要向 WebView 中的 html 内容

注入额外的 js 进行操作。这里记录一下在当前 WebView 控件中,获取 html 内容的方法。

 

运行效果:

02、获取 WebView 控件中,加载的 HTML 网页内容

 

1、首先在工程根目录下面放一个 test.html 文件,里面放入一些 html,作为测试内容: 

<!DOCTYPE html>

<html lang="en" xmlns="http://www.w3.org/1999/xhtml">
<head>
    <meta charset="utf-8" />
    <title></title>
</head>
<body>
    <!--绿色背景、居中-->
    <div style="width:400px;height:100px;color:black;background:#0f0;margin:0px auto;font-size:40px;">
        测试内容
    </div>
</body>
</html>

 

放在根目录下:

02、获取 WebView 控件中,加载的 HTML 网页内容

 

 2、在页面上放置一个 WebView 用来显示网页内容,另外放置两个按钮:

<Grid Background="White">
    <Grid.RowDefinitions>
        <RowDefinition Height="100"/>
        <RowDefinition Height="*"/>
    </Grid.RowDefinitions>
    <StackPanel HorizontalAlignment="Center" Orientation="Horizontal">
        <Button Content="方法 一" Click="Button_f1_Click"/>
        <Button Content="方法 二" Click="Button_f2_Click"/>
    </StackPanel> 
<WebView x:Name="webView" Grid.Row="2" Source="test.html"/>
</Grid>

 

 3、在 C# 页面:

 public MainPage()
 {
     this.InitializeComponent();

     this.Loaded += MainPage_Loaded;
     
     webView.ScriptNotify += webView_ScriptNotify;
 }

 // 把 appx 根目录下的 test.html 网页内容加载到 WebView 中
 async void MainPage_Loaded(object sender, RoutedEventArgs e)
 {
     string html = "";
     StorageFile file = await Windows.ApplicationModel.Package.Current.InstalledLocation.GetFileAsync("test.html");

     using (StreamReader sr = new StreamReader(await file.OpenStreamForReadAsync()))
     {
         html = sr.ReadToEnd();
     }

     // 如果网页内容是从网络下载的,则可以把 getHTML() 方法 注入到 html 中
     html += "<script>function getHTML(){ window.external.notify(document.documentElement.innerHTML)}</script>";

     webView.NavigateToString(html);
 }

 // 方法 一:调用注入的 js 方法
 async void Button_f1_Click(object sender, RoutedEventArgs e)
 {
    await webView.InvokeScriptAsync("getHTML", null);
     
 }

 void webView_ScriptNotify(object sender, NotifyEventArgs e)
 {
     // e.Value 中为方法调用的返回值
     Debug.WriteLine(e.Value);
 }


 // 方法 二:直接通过 html 中 window 对象的 eval 方法,将当前网页内容返回
 async void Button_f2_Click(object sender, RoutedEventArgs e)
 {
     // 直接将结果返回(返回值为 WebView 中的 html),并不会出发 ScriptNotify 事件
     var html = await webView.InvokeScriptAsync("eval", new[] { "document.documentElement.innerHTML" });

     Debug.WriteLine(html);
 }