重新想象 Windows 8.1 Store Apps (80) - 控件增强: WebView 之基本应用, POST 数据, 与 JavaScript 交互
作者:webabcd
介绍
重新想象 Windows 8.1 Store Apps 之控件增强
- WebView 的基本应用
- WebView 通过 POST 请求和 HTTP 头加载 url
- WebView 与 JavaScript 交互
示例
1、演示 WebView 的基本应用
WebView/Demo.xaml
- <Page
- x:Class="Windows81.Controls.WebView.Demo"
- xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
- xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
- xmlns:local="using:Windows81.Controls.WebView"
- 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="120 0 0 0">
- <Button Name="btnNavigateUrl" Content="导航到指定的 url" Click="btnNavigateUrl_Click" />
- <WebView Name="webView" Width="800" Height="2000" HorizontalAlignment="Left" Margin="0 10 0 0" />
- </StackPanel>
- </Grid>
- <Page.BottomAppBar>
- <AppBar x:Name="appBar" IsSticky="True" Padding="10,0">
- <StackPanel Name="buttonPanel" Orientation="Horizontal" HorizontalAlignment="Left">
- <AppBarButton Icon="Play" Label="SymbolIcon" />
- </StackPanel>
- </AppBar>
- </Page.BottomAppBar>
- </Page>
WebView/Demo.xaml.cs
- /*
- * 本例演示 WebView 的基本应用
- *
- * WebView - 内嵌浏览器
- *
- *
- * 提示:
- * 在 win8 中 WebView 会挡住所有元素(包括 AppBar),而在 win8.1 中不会再有这种情况了
- * 如果想看看 win8 中全屏 WebView 如何不挡 AppBar,以及如何使用 WebViewBrush 以达到不遮挡其他元素的目的,请参看:http://www.cnblogs.com/webabcd/archive/2013/03/04/2942242.html
- *
- * 注:win8 和 win8.1 中的 WebView 有很多区别,在 win8.1 中使用 WebView 请参考本系列教程,在 win8 中使用 WebView 请看考:http://www.cnblogs.com/webabcd/archive/2013/03/04/2942242.html
- */
- using System;
- using Windows.UI.Xaml;
- using Windows.UI.Xaml.Controls;
- using Windows.UI.Xaml.Media;
- namespace Windows81.Controls.WebView
- {
- public sealed partial class Demo : Page
- {
- public Demo()
- {
- this.InitializeComponent();
- }
- private void btnNavigateUrl_Click(object sender, RoutedEventArgs e)
- {
- // 导航到指定的 url
- webView.Navigate(new Uri("http://www.sina.com.cn/", UriKind.Absolute));
- // 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();
- RotateTransform rt = new RotateTransform();
- rt.Angle = ;
- // 支持 RenderTransform 了
- webView.RenderTransform = rt;
- // 支持 Opacity 了
- webView.Opacity = 0.3;
- // 支持 Focus 了
- // webView.Focus(FocusState.Programmatic);
- }
- void webView_FrameNavigationStarting(Windows.UI.Xaml.Controls.WebView sender, WebViewNavigationStartingEventArgs args)
- {
- // 是否取消此 url 的加载
- // args.Cancel = true;
- // args.Uri
- }
- void webView_FrameContentLoading(Windows.UI.Xaml.Controls.WebView sender, WebViewContentLoadingEventArgs args)
- {
- // args.Uri
- }
- void webView_FrameDOMContentLoaded(Windows.UI.Xaml.Controls.WebView sender, WebViewDOMContentLoadedEventArgs args)
- {
- // args.Uri
- }
- void webView_FrameNavigationCompleted(Windows.UI.Xaml.Controls.WebView sender, WebViewNavigationCompletedEventArgs args)
- {
- // 导航是否成功
- // args.IsSuccess
- // 导航失败时,失败原因的 WebErrorStatus 枚举
- // args.WebErrorStatus
- }
- void webView_NavigationStarting(Windows.UI.Xaml.Controls.WebView sender, WebViewNavigationStartingEventArgs args)
- {
- // 是否取消此 url 的加载
- // args.Cancel = true;
- // args.Uri
- }
- void webView_ContentLoading(Windows.UI.Xaml.Controls.WebView sender, WebViewContentLoadingEventArgs args)
- {
- // args.Uri
- }
- void webView_DOMContentLoaded(Windows.UI.Xaml.Controls.WebView sender, WebViewDOMContentLoadedEventArgs args)
- {
- // args.Uri
- }
- void webView_NavigationCompleted(Windows.UI.Xaml.Controls.WebView sender, WebViewNavigationCompletedEventArgs args)
- {
- // 导航是否成功
- // args.IsSuccess
- // 导航失败时,失败原因的 WebErrorStatus 枚举
- // args.WebErrorStatus
- }
- // 在 WebView 尝试下载不受支持的文件时发生
- void webView_UnviewableContentIdentified(Windows.UI.Xaml.Controls.WebView sender, WebViewUnviewableContentIdentifiedEventArgs args)
- {
- // 引用页
- // args.Referrer
- // args.Uri
- }
- // 在 WebView 对 SmartScreen 筛选器报告为不安全的内容显示警告页面时发生
- void webView_UnsafeContentWarningDisplaying(Windows.UI.Xaml.Controls.WebView sender, object args)
- {
- }
- // 当脚本运行时,可能会导致 app 无响应。此事件会定期执行,然后可查看 ExecutionTime 属性,如果要暂停脚本,则将 StopPageScriptExecution 属性设置为 true 即可
- void webView_LongRunningScriptDetected(Windows.UI.Xaml.Controls.WebView sender, WebViewLongRunningScriptDetectedEventArgs args)
- {
- // 获取 WebView 执行的一个长时间运行的脚本的运行时间(单位:毫秒)
- // args.ExecutionTime
- // 是否暂停在 WebView 中执行的已运行很长时间的脚本
- // args.StopPageScriptExecution
- }
- }
- }
2、演示如何通过 POST 请求和 HTTP 头加载 url
WebView/Post.xaml
- <Page
- x:Class="Windows81.Controls.WebView.Post"
- xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
- xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
- xmlns:local="using:Windows81.Controls.WebView"
- 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="120 0 0 0">
- <WebView Name="webView" Width="800" Height="300" HorizontalAlignment="Left" />
- </StackPanel>
- </Grid>
- </Page>
WebView/Post.xaml.cs
- /*
- * 本例演示如何通过 POST 请求和 HTTP 头加载 url
- *
- * WebView - 内嵌浏览器
- *
- *
- * 提示:
- * 在 win8 中 WebView 会挡住所有元素(包括 AppBar),而在 win8.1 中不会再有这种情况了
- * 如果想看看 win8 中全屏 WebView 如何不挡 AppBar,以及如何使用 WebViewBrush 以达到不遮挡其他元素的目的,请参看:http://www.cnblogs.com/webabcd/archive/2013/03/04/2942242.html
- *
- * 注:win8 和 win8.1 中的 WebView 有很多区别,在 win8.1 中使用 WebView 请参考本系列教程,在 win8 中使用 WebView 请看考:http://www.cnblogs.com/webabcd/archive/2013/03/04/2942242.html
- */
- using System;
- using Windows.UI.Xaml;
- using Windows.UI.Xaml.Controls;
- using Windows.Web.Http;
- namespace Windows81.Controls.WebView
- {
- public sealed partial class Post : Page
- {
- public Post()
- {
- this.InitializeComponent();
- this.Loaded += Post_Loaded;
- }
- void Post_Loaded(object sender, RoutedEventArgs e)
- {
- HttpRequestMessage httpRequestMessage = new HttpRequestMessage(HttpMethod.Post, new Uri("http://localhost:39630/WebViewPost.aspx")); // 此测试 aspx 在 WebServer 项目中
- // 构造 post 数据(无法 form 提交,因为试了很久,无法将 ContentType 设置为 "application/x-www-form-urlencoded")
- httpRequestMessage.Content = new HttpStringContent("hello webabcd");
- // 构造 http header 数据
- httpRequestMessage.Headers.Append("myHeader", "hello header");
- // NavigateWithHttpRequestMessage() - 通过 POST 请求和 HTTP 头加载 url
- webView.NavigateWithHttpRequestMessage(httpRequestMessage);
- }
- }
- }
服务端:
WebServer/WebViewPost.aspx.cs
- /*
- * 用于 WebView 演示如何通过 POST 请求和 HTTP 头加载 url
- */
- using System;
- using System.Collections.Generic;
- using System.IO;
- using System.Linq;
- using System.Web;
- using System.Web.UI;
- using System.Web.UI.WebControls;
- namespace WebServer
- {
- public partial class WebViewPost : System.Web.UI.Page
- {
- protected void Page_Load(object sender, EventArgs e)
- {
- Request.InputStream.Position = ;
- StreamReader str = new StreamReader(Request.InputStream);
- string postData = str.ReadToEnd();
- str.Dispose();
- // 显示 post 过来的数据
- Response.Write("post data: " + postData);
- Response.Write("<br />");
- // 显示请求的一个自定义的 http 头
- Response.Write("my header: " + Request.Headers["myHeader"]);
- }
- }
- }
3、演示 WebView 如何与 JavaScript 交互
WebView/Interact.xaml
- <Page
- x:Class="Windows81.Controls.WebView.Interact"
- xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
- xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
- xmlns:local="using:Windows81.Controls.WebView"
- 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="120 0 0 0">
- <TextBlock Name="lblMsg" FontSize="14.667" />
- <Button Name="btnInvokeJavaScript" Content="app 调用 WebView 加载内容中的 JavaScript 函数" Click="btnInvokeJavaScript_Click" Margin="0 10 0 0" />
- <Button Name="btnAccessDOM" Content="通过 eval 访问 DOM" Click="btnAccessDOM_Click" Margin="0 10 0 0" />
- <Button Name="btnRegisterJavaScript" Content="通过 eval 向页面中注册 JavaScript 脚本" Click="btnRegisterJavaScript_Click" Margin="0 10 0 0" />
- <!--
- 通过 ms-appx-web 加载包内的 html 页面
- -->
- <WebView Name="webView" Width="400" Height="300" Source="ms-appx-web:///Controls/WebView/WebViewInteract.html" HorizontalAlignment="Left" Margin="0 10 0 0" />
- </StackPanel>
- </Grid>
- </Page>
WebView/Interact.xaml.cs
- /*
- * 本例演示 WebView 如何与 JavaScript 交互
- *
- * WebView - 内嵌浏览器
- * DocumentTitle - html 中的 title
- * DefaultBackgroundColor - html 中的背景色
- * InvokeScriptAsync() - 调用 JavaScript 中的指定函数,并返回执行结果
- * ScriptNotify - 当接收到从 JavaScript 发过来的数据时所触发的事件(事件参数:NotifyEventArgs),通过在 html 中调用 window.external.notify 来实现 js 调用 app
- *
- * NotifyEventArgs
- * Value - js 传递给 app 的数据
- *
- * 本例通过加载同目录下的 WebViewInteract.html 来演示 app 与 js 的交互
- *
- *
- *
- * 提示:
- * 在 win8 中 WebView 会挡住所有元素(包括 AppBar),而在 win8.1 中不会再有这种情况了
- * 如果想看看 win8 中全屏 WebView 如何不挡 AppBar,以及如何使用 WebViewBrush 以达到不遮挡其他元素的目的,请参看:http://www.cnblogs.com/webabcd/archive/2013/03/04/2942242.html
- *
- * 注:win8 和 win8.1 中的 WebView 有很多区别,在 win8.1 中使用 WebView 请参考本系列教程,在 win8 中使用 WebView 请看考:http://www.cnblogs.com/webabcd/archive/2013/03/04/2942242.html
- */
- /*
- * 特别注意:
- * 1、在 win8.1 中如果要允许外部网页引发 ScriptNotify 事件,则必须在 appxmanifest 中设置允许的 URI,必须是 https 协议的,类似如下
- * <ApplicationContentUriRules>
- * <Rule Match="https://aaa.aaa.aaa" Type="include" />
- * </ApplicationContentUriRules>
- * 2、如果使用的是本地 html 数据则无此限制,比如通过 NavigateToString 或 ms-appx-web 来加载 html 时
- * 3、另外如果是 http 的话,可以将 html 下载到本地,然后加载此 html,而 html 中的 url 引用则可以引用远程的(如果需要替换 html 中的 url 引用则可以参考 Local.xaml 的方式)
- */
- using System;
- using System.Collections.Generic;
- using Windows.UI.Popups;
- using Windows.UI.Xaml;
- using Windows.UI.Xaml.Controls;
- namespace Windows81.Controls.WebView
- {
- public sealed partial class Interact : Page
- {
- public Interact()
- {
- this.InitializeComponent();
- webView.ScriptNotify += webView_ScriptNotify;
- webView.NavigationCompleted += webView_NavigationCompleted;
- }
- void webView_NavigationCompleted(Windows.UI.Xaml.Controls.WebView sender, WebViewNavigationCompletedEventArgs args)
- {
- if (args.IsSuccess)
- {
- lblMsg.Text = "html title: " + webView.DocumentTitle;
- lblMsg.Text += Environment.NewLine;
- lblMsg.Text += "html backgroundColor: " + webView.DefaultBackgroundColor.ToString();
- }
- }
- async void webView_ScriptNotify(object sender, NotifyEventArgs e)
- {
- // 获取 js 传递过来的数据(js 端通向 app 传递数据的方法:window.external.notify('js to app');)
- await new MessageDialog(e.Value).ShowAsync();
- }
- // app 调用 js
- private async void btnInvokeJavaScript_Click(object sender, RoutedEventArgs e)
- {
- List<string> arguments = new List<string> { "webabcd" };
- // 调用 js 方法:sayHelloToJs('webabcd'); 并返回结果
- string result = await webView.InvokeScriptAsync("sayHelloToJs", arguments);
- await new MessageDialog(result).ShowAsync();
- }
- // 通过 eval 方式访问 DOM
- private async void btnAccessDOM_Click(object sender, RoutedEventArgs e)
- {
- // 获取 document.title 的值
- List<string> arguments = new List<string> { "document.title" };
- string result = await webView.InvokeScriptAsync("eval", arguments);
- await new MessageDialog(result).ShowAsync();
- }
- // 通过 eval 向页面中注册 JavaScript 脚本
- private async void btnRegisterJavaScript_Click(object sender, RoutedEventArgs e)
- {
- // 向 html 中注册脚本
- List<string> arguments = new List<string> { "function xxx(){return '由 app 向 html 注册的脚本返回的数据';}" };
- await webView.InvokeScriptAsync("eval", arguments);
- // 调用刚刚注册的脚本
- string result = await webView.InvokeScriptAsync("xxx", null);
- await new MessageDialog(result).ShowAsync();
- }
- }
- }
HTML:
WebView/WebViewInteract.html
- <!--此 html 用于演示 app 与 js 间的交互-->
- <!doctype html>
- <html>
- <head>
- <title>I am html title</title>
- <script type='text/javascript'>
- function sayHelloToJs(name) {
- return 'app to js: ' + name;
- }
- function sayHelloToApp() {
- // 传递数据给 app
- window.external.notify('js to app');
- }
- </script>
- </head>
- <body>
- <input type='button' onclick='sayHelloToApp();' value='js 调用 app 中的方法' />
- </body>
- </html>
OK
[源码下载]
重新想象 Windows 8.1 Store Apps (80) - 控件增强: WebView 之基本应用, POST 数据, 与 JavaScript 交互的更多相关文章
- 重新想象 Windows 8.1 Store Apps (81) - 控件增强: WebView 之加载本地 html, 智能替换 html 中的 url 引用, 通过 Share Contract 分享 WebView 中的内容, 为 WebView 截图
[源码下载] 重新想象 Windows 8.1 Store Apps (81) - 控件增强: WebView 之加载本地 html, 智能替换 html 中的 url 引用, 通过 Share Co ...
- 重新想象 Windows 8.1 Store Apps (81) - 控件增强: 加载本地 html, 智能替换 html 中的 url 引用, 通过 Share Contract 分享 WebView 中的内容, 为 WebView 截图
原文:重新想象 Windows 8.1 Store Apps (81) - 控件增强: 加载本地 html, 智能替换 html 中的 url 引用, 通过 Share Contract 分享 Web ...
- 重新想象 Windows 8.1 Store Apps (78) - 控件增强: ScrollViewer, FlipView, Popup
[源码下载] 重新想象 Windows 8.1 Store Apps (78) - 控件增强: ScrollViewer, FlipView, Popup 作者:webabcd 介绍重新想象 Wind ...
- 重新想象 Windows 8.1 Store Apps (77) - 控件增强: 文本类控件的增强, 部分控件增加了 Header 属性和 HeaderTemplate 属性, 部分控件增加了 PlaceholderText 属性
[源码下载] 重新想象 Windows 8.1 Store Apps (77) - 控件增强: 文本类控件的增强, 部分控件增加了 Header 属性和 HeaderTemplate 属性, 部分控件 ...
- 重新想象 Windows 8.1 Store Apps (79) - 控件增强: MediaElement, Frame
[源码下载] 重新想象 Windows 8.1 Store Apps (79) - 控件增强: MediaElement, Frame 作者:webabcd 介绍重新想象 Windows 8.1 St ...
- 重新想象 Windows 8.1 Store Apps (93) - 控件增强: GridView, ListView
[源码下载] 重新想象 Windows 8.1 Store Apps (93) - 控件增强: GridView, ListView 作者:webabcd 介绍重新想象 Windows 8.1 Sto ...
- 重新想象 Windows 8 Store Apps (8) - 控件之 WebView
原文:重新想象 Windows 8 Store Apps (8) - 控件之 WebView [源码下载] 重新想象 Windows 8 Store Apps (8) - 控件之 WebView 作者 ...
- 重新想象 Windows 8.1 Store Apps 系列文章索引
[源码下载] [重新想象 Windows 8 Store Apps 系列文章] 重新想象 Windows 8.1 Store Apps 系列文章索引 作者:webabcd 1.重新想象 Windows ...
- 重新想象 Windows 8.1 Store Apps (75) - 新增控件: Hub, Hyperlink
[源码下载] 重新想象 Windows 8.1 Store Apps (75) - 新增控件: Hub, Hyperlink 作者:webabcd 介绍重新想象 Windows 8.1 Store A ...
随机推荐
- GitHub上排名前100的Android开源库介绍(来自github)
本项目主要对目前 GitHub 上排名前 100 的 Android 开源库进行简单的介绍,至于排名完全是根据 GitHub 搜索 Java 语言选择 (Best Match) 得到的结果,然后过滤了 ...
- Spring3系列3 -- JavaConfig
Spring3系列3-JavaConfig-1 从Spring3开始,加入了JavaConfig特性,JavaConfig特性允许开发者不必在Spring的xml配置文件中定义bean,可以在Java ...
- PHP vs Python
最近在搞微信公众号方面的开发,发现很多开发微信公众号都使用PHP来开发,由于我之前开发Web端喜欢使用Python,所以从Quora网站找出一篇Which-is-better-PHP-or-Pytho ...
- Oracle数据库入门——物化视图日志结构
物化视图的快速刷新要求基本必须建立物化视图日志,这篇文章简单描述一下物化视图日志中各个字段的含义和用途. 物化视图日志的名称为MLOG$_后面跟基表的名称,如果表名的长度超过20位,则只取前20位,当 ...
- mysql日期类型默认值'0000-00-00'容错处理
mysql日期默认值'0000-00-00'惹的祸 .net连mysql数据库时,如果表里有字段是日期型且值是‘0000-00-00’时,会报错.在C#里面日期不可能是那样的.或许是最小日期定义的差别 ...
- HTTP 详解一 -- 转
HTTP是一个属于应用层的面向对象的协议,由于其简捷.快速的方式,适用于分布式超媒体信息系统.它于1990年提出,经过几年的使用与发展,得到不断地完善和扩展.目前在WWW中使用的是HTTP/1.0的第 ...
- 比特(bit)与字节(byte)区别,站位比较
“字节”(Byte) “比特”(Bit) 当你进行网络下载的时候它们会经常出现,同时你获取的速度指示也都以比特/每秒或者字节/每秒来显示. 现在就来弄清楚比特(Bit).字节(Byte)和千字节(Kb ...
- [0x01 用Python讲解数据结构与算法] 关于数据结构和算法还有编程
忍耐和坚持虽是痛苦的事情,但却能渐渐地为你带来好处. ——奥维德 一.学习目标 · 回顾在计算机科学.编程和问题解决过程中的基本知识: · 理解“抽象”在问题解决过程中的重要作用: · 理解并实现抽象 ...
- AssetBundle系列——场景资源之解包(二)
本篇接着上一篇继续和大家分享场景资源这一主题,主要包括两个方面: (1)加载场景 场景异步加载的代码比较简单,如下所示: private IEnumerator LoadLevelCoroutine( ...
- PhoneCat App 教程
https://docs.angularjs.org/tutorial AngularJS教程第一篇文章的翻译,因为我在看中文版的AngularJS的翻译的时候,发现第一篇文章翻译的不准确,很有可能是 ...