WebView webview = (WebView) findComponentById(ResourceTable.Id_webview);

2. 通过WebView加载Web页面


WebView加载页面分为加载Web页面和加载本地Web页面两种情况,接下来我们将分别进行介绍。

1.WebView加载网络Web页面

跟Android类似,要访问网络,我们首先要配置网络访问权限,在config.json的"module"节点最后,添加上网络权限代码

module": {
…
“reqPermissions”: [
{
“name”: “ohos.permission.INTERNET”
}
]
}

2 设置访问模式

鸿蒙的默认是https访问模式,如果您的请求网址是http开头的,请在config.json文件中的deviceConfig下,添加如下设置

“deviceConfig”: {
“default”: {
“network”: {
“cleartextTraffic”: true
}
}
},

在"slice/MainAbilitySlice.java"文件中通过webview.load(String url)方法访问具体的Web页面,通过WebConfig类对WebView组件的行为进行配置,示例代码如下:

WebConfig webConfig = webview.getWebConfig();
// WebView加载URL,其中urlTextField为输入URL的TextField组件
webview.load(urlTextField.getText());

在Web页面进行链接跳转时,WebView默认会打开目标网址,通过WebAgent对象可以定制该行为,示例代码如下:

webview.setWebAgent(new WebAgent() {
@Override
public boolean isNeedLoadUrl(WebView webView, ResourceRequest request) {
if (request == null || request.getRequestUrl() == null) {
LogUtil.info(TAG,“WebAgent isNeedLoadUrl:request is null.”);
return false;
}
String url = request.getRequestUrl().toString();
if (url.startsWith(“http:”) || url.startsWith(“https:”)) {
webView.load(url);
return false;
} else {
return super.isNeedLoadUrl(webView, request);
}
}
});

除此之外,WebAgent对象还提供了相关的回调函数以观测页面状态的变更,如onLoadingPage、onPageLoaded、onError等方法。WebView提供Navigator类进行历史记录的浏览和处理,通过getNavigator()方法获取该类的对象,使用canGoBack()或canGoForward()方法检查是否可以向后或向前浏览,使用goBack()或goForward()方法向后或向前浏览,示例代码如下:

Navigator navigator = webView.getNavigator();
if (navigator.canGoBack()) {
navigator.goBack();
}
if (navigator.canGoForward()) {
navigator.goForward();
}

3.WebView加载本地Web页面


将本地的HTML文件放在"resources/rawfile/"目录下,在本教程中命名为test.html。在HarmonyOS系统中,WebView要访问本地Web文件,需要通过DataAbility的方式进行访问,DataAbility的具体使用方法可以参考开发

DataAbility,关于DataAbility的相关知识,后面也会继续展示,谁让他是最重要的内容呢。

在"entry/src/main/config.json"中完成DataAbility的声明,示例代码如下:

module": {
…
“abilities”: [
{
“name”: “com.huawei.codelab.DataAbility”,
“type”: “data”,
“uri”: “dataability://com.example.harmonyosdemo.DataAbility”
}
]
}

另外需要实现一个DataAbility,通过实现openRawFile(Uri uri, String mode)方法,完成WebView对本地Web页面的访问,示例代码如下:

public class DataAbility extends Ability {
…
@Override
public RawFileDescriptor openRawFile(Uri uri, String mode) throws FileNotFoundException {
if (uri == null) {;
return super.openRawFile(uri, mode);
}
String path = uri.getEncodedPath();
int splitIndex = path.indexOf(‘/’, 1);
String providerName = Uri.decode(path.substring(1, splitIndex));
String rawFilePath = Uri.decode(path.substring(splitIndex + 1));
RawFileDescriptor rawFileDescriptor = null;
try {
rawFileDescriptor = getResourceManager().getRawFileEntry(rawFilePath).openRawFileDescriptor();
} catch (IOException e) {
// 异常处理
}
return rawFileDescriptor;
}
}

在"slice/MainAbilitySlice.java"中声明需要访问的文件路径,通过webview.load(String url)方法加载本地Web页面,可以通过WebConfig类的对象对WebView访问DataAbility的能力进行配置,示例代码如下:

private static final String URL_LOCAL = “dataability://com.huawei.codelab.DataAbility/resources/rawfile/test.html”;
// 配置是否支持访问DataAbility资源,默认为true
webConfig.setDataAbilityPermit(true);
webview.load(URL_LOCAL);

4. 实现应用与WebView中的Web页面间的通信


本教程以本地Web页面"resources/rawfile/test.html"为例介绍如何实现应用与WebView中的Web页面间交互。

首先需要对WebConfig进行配置,使能WebView与Web页面JavaScript交互的能力,示例代码如下:

// 配置是否支持JavaScript,默认值为false
webConfig.setJavaScriptPermit(true);

1.应用调用Web页面

在"resources/rawfile/test.html"中编写callJS方法,待应用调用,示例代码如下:

在"slice/MainAbilitySlice.java"中实现应用对JavaScript的调用,示例代码如下:

webview.executeJs(“javascript:callJS(‘这是来自JavaSlice的消息’)”, msg -> {
// 在这里处理Js的方法的返回值
});

我们可以通过setBrowserAgent方法设置自定义BrowserAgent对象,以观测JavaScript事件及通知等,通过复写onJsMessageShow方法来接管Web页面弹出Alert对话框的事件,示例代码如下:

webview.setBrowserAgent(new BrowserAgent(this) {
@Override
public boolean onJsMessageShow(WebView webView, String url, String message, boolean isAlert, JsMessageResult result) {
LogUtil.info(TAG,"BrowserAgent onJsMessageShow : " + message);
if (isAlert) {
// 将Web页面的alert对话框改为ToastDialog方式提示
new ToastDialog(getApplicationContext()).setText(message).setAlignment(LayoutAlignment.CENTER).show();
// 对弹框进行确认处理
result.confirm();
return true;
} else {
return super.onJsMessageShow(webView, url, message, isAlert, result);
}
}
});

2.Web页面使用JavaScript调用应用

在"resources/rawfile/test.html"中编写按钮,当按钮被点击时实现JavaScript对应用的调用,示例代码如下:

调用Java方法

在"slice/MainAbilitySlice.java"中实现应用对JavaScript发起的调用的响应,示例代码如下:

private static final String JS_NAME = “JsCallJava”;
webview.addJsCallback(JS_NAME, str -> {
// 处理接收到的JavaScript发送来的消息,本教程通过ToastDialog提示确认收到Web页面发来的消息
new ToastDialog(this).setText(str).setAlignment(LayoutAlignment.CENTER).show();
// 返回给JavaScript
return “Js Call Java Success”;
});

总结


通过上面的完整代码,我们已经完成了webbiew的基本使用

仓库地址:https://github.com/ITmxs/hm_webview

第二步删除默认代码


打开index.hml文件,里面有默认代码如下:

山茶

第三步,开始学习


首先将图片放到common文件夹下面的images里面,注意,我的图片文件名是flutter.png,

从上面布局效果图可以看到,界面主要由image组件和text组件组成,我们现在index.html中添加image组件和text组件,并添加对应的class,用于设置组件的显示效果,代码如下:


translate 
 

   rotate 
 

   rotateY 
 

   scale 
 

   opacity

第四步,为页面设计样式


在这个任务中,我们将一起为任务二中写好的页面添加样式,上面所有的组件都定义了class属性,它对应的样式都定义在index.css中,有关css更多的知识可以参考css语法参考。

这部分定义了整个页面中各个组件的样式。在index.css中先添加如下代码:

.container {
background-color: #F8FCF5;
flex-direction: column;
justify-content: center;
align-items: center;
}
.img {
margin-top: 10px;
height: 100px;
width: 100px;
animation-timing-function: ease;
animation-duration: 2s;
animation-delay: 0s;
animation-fill-mode: forwards;
animation-iteration-count: infinite;
}
.text {
font-size: 20px;
}

.img-translate {

在这个任务中,我们将一起为任务二中写好的页面添加样式,上面所有的组件都定义了class属性,它对应的样式都定义在index.css中,有关css更多的知识可以参考css语法参考。

这部分定义了整个页面中各个组件的样式。在index.css中先添加如下代码:

.container {
background-color: #F8FCF5;
flex-direction: column;
justify-content: center;
align-items: center;
}
.img {
margin-top: 10px;
height: 100px;
width: 100px;
animation-timing-function: ease;
animation-duration: 2s;
animation-delay: 0s;
animation-fill-mode: forwards;
animation-iteration-count: infinite;
}
.text {
font-size: 20px;
}
.img-translate {