背水一战 Windows 10 (63) - 控件(WebView): 基础知识, 加载 html, http, https, ms-appx-web:///, embedded resource, ms-appdata:///, ms-local-stream://
作者:webabcd
介绍
背水一战 Windows 10 之 控件(WebView)
- 基础知识
- 加载指定的 html
- 加载指定的 url(http, https, ms-appx-web:///, embedded resource, ms-appdata:///)
- 结合 IUriToStreamResolver 可以实现自定义所有请求(包括 html 的 url 以及 html 内所有引用的 url)返回的内容(ms-local-stream://)
示例
1、演示 WebView 的基础知识
Controls/WebViewDemo/WebViewDemo1.xaml
<Page
x:Class="Windows10.Controls.WebViewDemo.WebViewDemo1"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="using:Windows10.Controls.WebViewDemo"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
mc:Ignorable="d"> <Grid Background="Transparent">
<StackPanel Margin="10 0 10 10"> <Button Name="btnNavigateUrl" Content="加载指定的 url" Click="btnNavigateUrl_Click" Margin="5" /> <WebView Name="webView" Width="800" Height="400" HorizontalAlignment="Left" Margin="5" /> </StackPanel>
</Grid> </Page>
Controls/WebViewDemo/WebViewDemo1.xaml.cs
/*
* WebView - 内嵌浏览器控件(继承自 FrameworkElement, 请参见 /Controls/BaseControl/FrameworkElementDemo/)
*
*
* 本例用于演示 WebView 的基础知识
*/ using System;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls; namespace Windows10.Controls.WebViewDemo
{
public sealed partial class WebViewDemo1 : Page
{
public WebViewDemo1()
{
this.InitializeComponent();
} private void btnNavigateUrl_Click(object sender, RoutedEventArgs e)
{
// 加载指定的 url
webView.Navigate(new Uri("http://webabcd.cnblogs.com/", UriKind.Absolute)); // 获取或设置浏览器的 url
// webView.Source = new Uri("http://webabcd.cnblogs.com/", UriKind.Absolute); // web 页面中的某一个 frame 加载前
webView.FrameNavigationStarting += webView_FrameNavigationStarting;
// web 页面中的某一个 frame 加载中
webView.FrameContentLoading += webView_FrameContentLoading;
// web 页面中的某一个 frame 的 DOM 加载完成
webView.FrameDOMContentLoaded += webView_FrameDOMContentLoaded;
// web 页面中的某一个 frame 导航完成(成功或失败)
webView.FrameNavigationCompleted += webView_FrameNavigationCompleted; // web 页面加载前
webView.NavigationStarting += webView_NavigationStarting;
// web 页面加载中
webView.ContentLoading += webView_ContentLoading;
// web 页面的 DOM 加载完成
webView.DOMContentLoaded += webView_DOMContentLoaded;
// web 页面导航完成(成功或失败)
webView.NavigationCompleted += webView_NavigationCompleted; // 当脚本运行时,可能会导致 app 无响应。此事件会定期执行,然后可查看 ExecutionTime 属性,如果要暂停脚本,则将 StopPageScriptExecution 属性设置为 true 即可
webView.LongRunningScriptDetected += webView_LongRunningScriptDetected;
// 在 WebView 对 SmartScreen 筛选器报告为不安全的内容显示警告页面时发生
webView.UnsafeContentWarningDisplaying += webView_UnsafeContentWarningDisplaying;
// 在 WebView 尝试下载不受支持的文件时发生
webView.UnviewableContentIdentified += webView_UnviewableContentIdentified; // 用于导航 web 的一系列 api,顾名思义,不解释了
// webView.CanGoBack;
// webView.GoBack();
// webView.CanGoForward;
// webView.GoForward();
// webView.Stop();
// webView.Refresh(); // 设置焦点
// webView.Focus(FocusState.Programmatic); // 清除 WebView 的缓存和 IndexedDB 数据
// await WebView.ClearTemporaryWebDataAsync(); // WebView 在实例化时可以指定其是托管在 UI 线程(WebViewExecutionMode.SameThread)还是托管在非 UI 线程(WebViewExecutionMode.SeparateThread),默认是托管在 UI 线程的
// WebView wv = new WebView(WebViewExecutionMode.SeparateThread); // 获知 WebView 是托管在 UI 线程还是非 UI 线程
// WebViewExecutionMode executionMode = webView.ExecutionMode;
} void webView_FrameNavigationStarting(WebView sender, WebViewNavigationStartingEventArgs args)
{
// 是否取消此 url 的加载
// args.Cancel = true; // args.Uri
}
void webView_FrameContentLoading(WebView sender, WebViewContentLoadingEventArgs args)
{
// args.Uri
}
void webView_FrameDOMContentLoaded(WebView sender, WebViewDOMContentLoadedEventArgs args)
{
// args.Uri
}
void webView_FrameNavigationCompleted(WebView sender, WebViewNavigationCompletedEventArgs args)
{
// 导航是否成功
// args.IsSuccess // 导航失败时,失败原因的 WebErrorStatus 枚举
// args.WebErrorStatus
} void webView_NavigationStarting(WebView sender, WebViewNavigationStartingEventArgs args)
{
// 是否取消此 url 的加载
// args.Cancel = true; // args.Uri
}
void webView_ContentLoading(WebView sender, WebViewContentLoadingEventArgs args)
{
// args.Uri
}
void webView_DOMContentLoaded(WebView sender, WebViewDOMContentLoadedEventArgs args)
{
// args.Uri
}
void webView_NavigationCompleted(WebView sender, WebViewNavigationCompletedEventArgs args)
{
// 导航是否成功
// args.IsSuccess // 导航失败时,失败原因的 WebErrorStatus 枚举
// args.WebErrorStatus
} // 在 WebView 尝试下载不受支持的文件时发生
void webView_UnviewableContentIdentified(WebView sender, WebViewUnviewableContentIdentifiedEventArgs args)
{
// 引用页
// args.Referrer // args.Uri
} // 在 WebView 对 SmartScreen 筛选器报告为不安全的内容显示警告页面时发生
void webView_UnsafeContentWarningDisplaying(WebView sender, object args)
{ } // 当脚本运行时,可能会导致 app 无响应。此事件会定期执行,然后可查看 ExecutionTime 属性,如果要暂停脚本,则将 StopPageScriptExecution 属性设置为 true 即可
void webView_LongRunningScriptDetected(WebView sender, WebViewLongRunningScriptDetectedEventArgs args)
{
// 获取 WebView 执行的一个长时间运行的脚本的运行时间(单位:毫秒)
// args.ExecutionTime // 是否暂停在 WebView 中执行的已运行很长时间的脚本
// args.StopPageScriptExecution
}
}
}
2、演示 WebView 如何加载 html, http, https, ms-appx-web:///, embedded resource, ms-appdata:///, ms-local-stream://
Controls/WebViewDemo/demo1.html
<b>i am demo1.html</b>
Controls/WebViewDemo/demo2.html
<b>i am demo2.html</b>
Controls/WebViewDemo/demo3.html
<b>i am demo3.html</b>
Controls/WebViewDemo/demo4.html
<!DOCTYPE html>
<html>
<head>
<link href="css.css" rel="stylesheet" />
</head>
<body>
<b>i am demo4.html</b>
</body>
</html>
Controls/WebViewDemo/WebViewDemo2.xaml
<Page
x:Class="Windows10.Controls.WebViewDemo.WebViewDemo2"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="using:Windows10.Controls.WebViewDemo"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
mc:Ignorable="d"> <Grid Background="Transparent">
<StackPanel Margin="10 0 10 10"> <Button Name="btnNavigate" Content="通过 Navigate 加载指定的 url" Click="btnNavigate_Click" Margin="5" />
<Button Name="btnSource" Content="通过 Source 获取或设置当前的 url" Click="btnSource_Click" Margin="5" />
<Button Name="btnNavigateToString" Content="通过 NavigateToString 加载指定的 html" Click="btnNavigateToString_Click" Margin="5" /> <Button Name="btnMsAppxWeb" Content="加载指定的 ms-appx-web:/// 协议地址(Package 内的数据)" Click="btnMsAppxWeb_Click" Margin="5" />
<Button Name="btnEmbeddedResource" Content="加载指定的嵌入式资源(Package 内的数据)" Click="btnEmbeddedResource_Click" Margin="5" />
<Button Name="btnMsAppdata" Content="加载指定的 ms-appdata:/// 协议地址(Application 内的数据)" Click="btnMsAppdata_Click" Margin="5" />
<Button Name="btnMsLocalStream" Content="加载指定的 ms-local-stream:// 协议地址" Click="btnMsLocalStream_Click" Margin="5" /> <WebView Name="webView" Width="800" Height="400" HorizontalAlignment="Left" Margin="5" /> </StackPanel>
</Grid> </Page>
Controls/WebViewDemo/WebViewDemo2.xaml.cs
/*
* WebView - 内嵌浏览器控件(继承自 FrameworkElement, 请参见 /Controls/BaseControl/FrameworkElementDemo/)
*
*
* 本例用于演示
* 1、WebView 如何加载指定的 html
* 2、WebView 如何加载指定的 url(http, https, ms-appx-web:///, embedded resource, ms-appdata:///)
* 3、WebView 结合 IUriToStreamResolver 可以实现自定义所有请求(包括 html 的 url 以及 html 内所有引用的 url)返回的内容(ms-local-stream://)
*/ using System;
using System.IO;
using System.Reflection;
using System.Threading.Tasks;
using Windows.Foundation;
using Windows.Security.Cryptography;
using Windows.Storage;
using Windows.Storage.Streams;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
using Windows.Web; namespace Windows10.Controls.WebViewDemo
{
public sealed partial class WebViewDemo2 : Page
{
public WebViewDemo2()
{
this.InitializeComponent();
} private void btnNavigate_Click(object sender, RoutedEventArgs e)
{
// 通过 Navigate 加载指定的 url
webView.Navigate(new Uri("http://webabcd.cnblogs.com/", UriKind.Absolute));
} private void btnSource_Click(object sender, RoutedEventArgs e)
{
// 通过 Source 获取或设置当前的 url
webView.Source = new Uri("https://www.baidu.com", UriKind.Absolute);
} private void btnNavigateToString_Click(object sender, RoutedEventArgs e)
{
// 通过 NavigateToString 加载指定的 html
webView.NavigateToString("<b>i am webabcd</b>");
} private void btnMsAppxWeb_Click(object sender, RoutedEventArgs e)
{
// 加载指定的 ms-appx-web:/// 协议地址(Package 内的数据)
webView.Navigate(new Uri("ms-appx-web:///Controls/WebViewDemo/demo1.html", UriKind.Absolute));
} private void btnEmbeddedResource_Click(object sender, RoutedEventArgs e)
{
// 获取 Package 内嵌入式资源数据
Assembly assembly = typeof(WebViewDemo2).GetTypeInfo().Assembly;
Stream stream = assembly.GetManifestResourceStream("Windows10.Controls.WebViewDemo.demo2.html"); using (StreamReader reader = new StreamReader(stream))
{
string html = reader.ReadToEnd();
webView.NavigateToString(html);
}
} private async void btnMsAppdata_Click(object sender, RoutedEventArgs e)
{
// 将程序包内的 html 文件复制到 ApplicationData 中的 LocalFolder
StorageFolder localFolder = await ApplicationData.Current.LocalFolder.CreateFolderAsync("webabcdTest", CreationCollisionOption.OpenIfExists);
StorageFile htmlFile = await StorageFile.GetFileFromApplicationUriAsync(new Uri("ms-appx:///Controls/WebViewDemo/demo3.html"));
await htmlFile.CopyAsync(localFolder, "demo3.html", NameCollisionOption.ReplaceExisting); // 加载指定的 ms-appdata:/// 协议地址(Application 内的数据)
string url = "ms-appdata:///local/webabcdTest/demo3.html";
webView.Navigate(new Uri(url));
} private void btnMsLocalStream_Click(object sender, RoutedEventArgs e)
{
// 构造可传递给 NavigateToLocalStreamUri() 的 URI(即 ms-local-stream:// 协议的 URI)
Uri url = webView.BuildLocalStreamUri("contentIdentifier", "/Controls/WebViewDemo/demo4.html"); // 在我的示例中,上面方法返回的 url 如下(协议是: ms-local-stream://appname_KEY/folder/file, 其中的 KEY 会根据 contentIdentifier 的不同而不同)
// "ms-local-stream://48c7dd54-1ef2-4db7-a75e-7e02c5eefd40_636f6e74656e744964656e746966696572/Controls/WebViewDemo/demo4.html" // 实例化一个实现 IUriToStreamResolver 接口的类
StreamUriWinRTResolver myResolver = new StreamUriWinRTResolver();
// 所有 url(包括 html 的 url 以及 html 内所有引用的 url)都会通过 StreamUriWinRTResolver 来返回数据流
webView.NavigateToLocalStreamUri(url, myResolver);
}
} // 实现 IUriToStreamResolver 接口(用于响应所有 url 请求,包括 html 的 url 以及 html 内所有引用的 url)
// 可以认为这就是一个为 WebView 服务的 http server
public sealed class StreamUriWinRTResolver : IUriToStreamResolver
{
// IUriToStreamResolver 接口只有一个需要实现的方法
// 根据当前请求的 uri 返回对应的内容流
public IAsyncOperation<IInputStream> UriToStreamAsync(Uri uri)
{
return GetContent(uri).AsAsyncOperation();
} // 根据当前请求的 uri 返回对应的内容流
private async Task<IInputStream> GetContent(Uri uri)
{
string path = uri.AbsolutePath;
string responseString = ""; switch (path)
{
case "/Controls/WebViewDemo/demo4.html":
StorageFile fileRead = await StorageFile.GetFileFromApplicationUriAsync(new Uri("ms-appx://" + path, UriKind.Absolute));
return await fileRead.OpenAsync(FileAccessMode.Read); case "/Controls/WebViewDemo/css.css":
responseString = "b { color: red; }";
break; default:
break;
} // string 转 IInputStream
IBuffer buffer = CryptographicBuffer.ConvertStringToBinary(responseString, BinaryStringEncoding.Utf8);
var stream = new InMemoryRandomAccessStream();
await stream.WriteAsync(buffer);
return stream.GetInputStreamAt();
}
}
}
OK
[源码下载]
背水一战 Windows 10 (63) - 控件(WebView): 基础知识, 加载 html, http, https, ms-appx-web:///, embedded resource, ms-appdata:///, ms-local-stream://的更多相关文章
- 背水一战 Windows 10 (76) - 控件(控件基类): Control - 基础知识, 焦点相关, 运行时获取 ControlTemplate 和 DataTemplate 中的元素
[源码下载] 背水一战 Windows 10 (76) - 控件(控件基类): Control - 基础知识, 焦点相关, 运行时获取 ControlTemplate 和 DataTemplate 中 ...
- 背水一战 Windows 10 (75) - 控件(控件基类): FrameworkElement - 基础知识, 相关事件, HorizontalAlignment, VerticalAlignment
[源码下载] 背水一战 Windows 10 (75) - 控件(控件基类): FrameworkElement - 基础知识, 相关事件, HorizontalAlignment, Vertical ...
- 背水一战 Windows 10 (66) - 控件(WebView): 监听和处理 WebView 的事件
[源码下载] 背水一战 Windows 10 (66) - 控件(WebView): 监听和处理 WebView 的事件 作者:webabcd 介绍背水一战 Windows 10 之 控件(WebVi ...
- 背水一战 Windows 10 (65) - 控件(WebView): 对 WebView 中的内容截图, 通过 Share Contract 分享 WebView 中的被选中的内容
[源码下载] 背水一战 Windows 10 (65) - 控件(WebView): 对 WebView 中的内容截图, 通过 Share Contract 分享 WebView 中的被选中的内容 作 ...
- 背水一战 Windows 10 (64) - 控件(WebView): 加载指定 HttpMethod 的请求, 自定义请求的 http header, app 与 js 的交互
[源码下载] 背水一战 Windows 10 (64) - 控件(WebView): 加载指定 HttpMethod 的请求, 自定义请求的 http header, app 与 js 的交互 作者: ...
- 背水一战 Windows 10 (46) - 控件(ScrollViewer 基础): ScrollViewer, ScrollBar, ScrollContentPresenter
[源码下载] 背水一战 Windows 10 (46) - 控件(ScrollViewer 基础): ScrollViewer, ScrollBar, ScrollContentPresenter 作 ...
- 背水一战 Windows 10 (50) - 控件(集合类): ItemsControl - 基础知识, 数据绑定, ItemsPresenter, GridViewItemPresenter, ListViewItemPresenter
[源码下载] 背水一战 Windows 10 (50) - 控件(集合类): ItemsControl - 基础知识, 数据绑定, ItemsPresenter, GridViewItemPresen ...
- 背水一战 Windows 10 (56) - 控件(集合类): ListViewBase - 基础知识, 拖动项
[源码下载] 背水一战 Windows 10 (56) - 控件(集合类): ListViewBase - 基础知识, 拖动项 作者:webabcd 介绍背水一战 Windows 10 之 控件(集合 ...
- 背水一战 Windows 10 (6) - 控件 UI: 字体的自动继承的特性, Style, ControlTemplate
[源码下载] 背水一战 Windows 10 (6) - 控件 UI: 字体的自动继承的特性, Style, ControlTemplate 作者:webabcd 介绍背水一战 Windows 10 ...
随机推荐
- leetcode62
使用排列组合计算公式来计算,注意使用long long型数据保证计算不会溢出. class Solution { public: int M, N; ; //从根到叶子有多少个分支,就表示有多少种路径 ...
- 制造业期刊-ZT
小虫一名英国博后,前阵发书,认识了很多机械制造领域的伙伴.得知我录用了多篇顶刊后,很多人私聊我求经验. 哎,哪里那么容易.回想过去5年,制造领域的期刊基本都被拒过一圈.当年自己投稿时就发现,制造顶刊的 ...
- Python介绍与安装
Python 是一种面向对象的解释型程序设计语言,支持支持面向过程.函数式和面向对象编程.另外,Python可以在Windows.UNIX等多个操作系统上使用. 为什么学编程 编程是一种工具,可以实现 ...
- js中子窗口调用父窗口中的变量、函数
- psdTohtml
https://github.com/anjorweb/fastHtml fastHtml 一个简单的psd直接导出html的工具 自己工作常用整理 适合单页面且采用DOM结构布局的H5页面,基于Ca ...
- Java学习笔记(二十三):final关键字
final关键字有三种使用场景: final修饰类 final修饰方法 final修饰变量 final修饰的类,不能再有子类继承. 只要满足以下条件就可以把一个类设计为final类: 不是专门为继承而 ...
- Python设计模式 - 基础 - 类/接口之间的六种关系
在程序中需要把世间万物抽象成相应的类,现实世界中物与物之间的关系和程序中类与类之间的关系相对应,因为世间万物是普遍联系的,所以程序中类与类之间也不是孤立的.在系统分析和框架设计中,根据面向对象机制的三 ...
- Js学习(3) 数组
数组本质: 本质上数组是特殊的对象,因此,数组中可以放入任何类型的数据,对象,数组,函数都行 它的特殊性在于键名是按次序排列好的整数 从0开始,是固定的,不用指定键名 如果数组中的元素仍是数组,则为多 ...
- 使用git开发的流程
1.git常用的主干,分支命令 查看分支 git branch 或者 git branch -v A) 创建分支 git branch Dev_samples_V1.0.0 B) 切换分支 git c ...
- 3U - 算菜价
妈妈每天都要出去买菜,但是回来后,兜里的钱也懒得数一数,到底花了多少钱真是一笔糊涂帐.现在好了,作为好儿子(女儿)的你可以给她用程序算一下了,呵呵. Input 输入含有一些数据组,每组数据包括菜种( ...