4.7【HarmonyOS鴻蒙開發】組件WebView
作者:韓茹
公司:程序咖(北京)科技有限公司
鴻蒙巴士專欄作家
WebView提供在應用中集成Web頁面的能力。
說明
- 請使用真機或模擬器運行查看WebView效果,預覽器不支持WebView顯示。
- 只有預置WebView能力的真機設備才支持WebView功能。具體請以實際設備支持情況為准。智能穿戴設備不支持WebView。
一、WebView的使用方法
WebView派生於通用組件Component,可以像普通組件一樣進行使用。
方式一:
1、在layout目錄下的xml文件中創建WebView。
<ohos.agp.components.webengine.WebView
ohos:id="$+id:webview"
ohos:height="match_parent"
ohos:width="match_parent">
</ohos.agp.components.webengine.WebView>
2、在MainAbility.java文件中,使用load方法加載Web頁面。
package com.example.hanruwebview.slice;
import com.example.hanruwebview.ResourceTable;
import ohos.aafwk.ability.AbilitySlice;
import ohos.aafwk.content.Intent;
import ohos.agp.components.webengine.WebView;
public class MainAbilitySlice extends AbilitySlice {
private static final String EXAMPLE_URL="https://www.harmonybus.net/";
@Override
public void onStart(Intent intent) {
super.onStart(intent);
super.setUIContent(ResourceTable.Layout_ability_main);
// 加載WebView
WebView webView = (WebView) findComponentById(ResourceTable.Id_webview1);
webView.getWebConfig() .setJavaScriptPermit(true); // 如果網頁需要使用JavaScript,增加此行;如何使用JavaScript下文有詳細介紹
final String url = EXAMPLE_URL; // EXAMPLE_URL由開發者自定義
webView.load(url);
}
}
因為我們要打開網絡,需要網絡訪問,那么就需要進行網絡授權,在config.json文件中添加以下授權信息:
"reqPermissions": [
{
"name": "ohos.permission.INTERNET"
}
]
結構如下:
這里我們打開的是鴻蒙巴士主頁:

方式二:
1、在ComponentContainer中創建WebView。
我們將Layout目錄下新建一個xml布局文件:layout_webview_demo.xml,我們不需要添加任何控件,只要在根布局中添加id屬性即可。
<?xml version="1.0" encoding="utf-8"?>
<DirectionalLayout
xmlns:ohos="http://schemas.huawei.com/res/ohos"
ohos:height="match_parent"
ohos:width="match_parent"
ohos:id="$+id:directionallayout1"
ohos:orientation="vertical">
</DirectionalLayout>
然后在在slice目錄下新建一個AbilitySlice,SecondAbilitySlice.java
package com.example.hanruwebview.slice;
import com.example.hanruwebview.ResourceTable;
import ohos.aafwk.ability.AbilitySlice;
import ohos.aafwk.content.Intent;
import ohos.agp.components.ComponentContainer;
import ohos.agp.components.DirectionalLayout;
import ohos.agp.components.webengine.WebView;
public class SecondAbilitySlice extends AbilitySlice {
private static final String EXAMPLE_URL="https://www.baidu.com/";
@Override
protected void onStart(Intent intent) {
super.onStart(intent);
super.setUIContent(ResourceTable.Layout_layout_webview_demo);
// 方法二:
WebView webView = new WebView(getContext());
webView.setWidth(ComponentContainer.LayoutConfig.MATCH_PARENT);
webView.setHeight(ComponentContainer.LayoutConfig.MATCH_PARENT);
webView.getWebConfig() .setJavaScriptPermit(true); // 如果網頁需要使用JavaScript,增加此行;如何使用JavaScript下文有詳細介紹
DirectionalLayout directionalLayout = (DirectionalLayout) findComponentById(ResourceTable.Id_directionallayout1);
directionalLayout.addComponent(webView);
}
}
2、加載Web頁面。
final String url = EXAMPLE_URL; // EXAMPLE_URL由開發者自定義
webView.load(url);
修改一下程序的入口:
package com.example.hanruwebview;
import com.example.hanruwebview.slice.MainAbilitySlice;
import com.example.hanruwebview.slice.SecondAbilitySlice;
import ohos.aafwk.ability.Ability;
import ohos.aafwk.content.Intent;
public class MainAbility extends Ability {
@Override
public void onStart(Intent intent) {
super.onStart(intent);
// super.setMainRoute(MainAbilitySlice.class.getName());
super.setMainRoute(SecondAbilitySlice.class.getName());
}
}
看一下效果:

二、定制網址加載行為
當Web頁面進行鏈接跳轉時,WebView默認會打開目標網址,通過以下方式可以定制該行為。
1、自定義WebAgent對象。
private class ExampleWebAgent extends WebAgent {
@Override
public boolean isNeedLoadUrl(WebView webView, ResourceRequest request) {
Uri uri = request.getRequestUrl();
if (EXAMPLE_URL.equals(uri.getDecodedHost())) {
// 由WebView通過默認方式處理
return false;
}
// 增加開發者自定義邏輯
return super.isNeedLoadUrl(webView, request);
}
}
2、設置自定義WebAgent至WebView。
webView.setWebAgent(new ExampleWebAgent());
三、瀏覽網頁歷史記錄
1、通過getNavigator方法獲取Navigator對象。
Navigator navigator = webView.getNavigator();
2、使用canGoBack()或canGoForward()檢查是否可以向后或向前瀏覽,使用goBack()或goForward()向后或向前瀏覽。
if (navigator.canGoBack()) {
navigator.goBack();
}
if (navigator.canGoForward()) {
navigator.goForward();
}
四、使用JavaScript
通過以下方式,可以建立應用和頁面間的JavaScript調用。
1、通過WebConfig啟用JavaScript。
webView.getWebConfig().setJavaScriptPermit(true);
2、根據實際需要選擇調用方式。
- 注入回調對象到頁面內容,並在頁面中調用該對象。
final String jsName = "JsCallbackToApp";
webview.addJsCallback(jsName, new JsCallback() {
@Override
public String onCallback(String msg) {
// 增加自定義處理
return "jsResult";
}
});
在頁面內通過JavaScript代碼調用注入對象。
function callToApp() {
if (window.JsCallbackToApp && window.JsCallbackToApp.call) {
var result = JsCallbackToApp.call("message from web");
}
}
- 在應用內調用頁面內的JavaScript方法。
webview.executeJs("javascript:callFuncInWeb()", new AsyncCallback<String>() {
@Override
public void onReceive(String msg) {
// 在此確認返回結果
}
});
五、觀測Web狀態
通過setWebAgent方法設置自定義WebAgent對象,以觀測頁面狀態變更等事件:
webview.setWebAgent(new WebAgent() {
@Override
public void onLoadingPage(WebView webView, String url, PixelMap favicon) {
super.onLoadingPage(webView, url, favicon);
// 頁面開始加載時自定義處理
}
@Override
public void onPageLoaded(WebView webView, String url) {
super.onPageLoaded(webView, url);
// 頁面加載結束后自定義處理
}
@Override
public void onLoadingContent(WebView webView, String url) {
super.onLoadingContent(webView, url);
// 加載資源時自定義處理
}
@Override
public void onError(WebView webView, ResourceRequest request, ResourceError error) {
super.onError(webView, request, error);
// 發生錯誤時自定義處理
}
});
六、觀測瀏覽事件
通過setBrowserAgent方法設置自定義BrowserAgent對象,以觀測JavaScript事件及通知等:
webview.setBrowserAgent(new BrowserAgent(this) {
@Override
public void onTitleUpdated(WebView webView, String title) {
super.onTitleUpdated(webView, title);
// 標題變更時自定義處理
}
@Override
public void onProgressUpdated(WebView webView, int newProgress) {
super.onProgressUpdated(webView, newProgress);
// 加載進度變更時自定義處理
}
});
七、加載資源文件或本地文件
出於安全考慮,WebView不支持直接通過File協議加載資源文件或本地文件,如應用需實現相關業務,可參考如下方式實現。
方式一:通過processResourceRequest方法訪問文件
1、通過setWebAgent方法設置自定義WebAgent對象,覆寫processResourceRequest方法。
webview.setWebAgent(new WebAgent() {
@Override
public ResourceResponse processResourceRequest(WebView webView, ResourceRequest request) {
final String authority = "example.com";
final String rawFile = "/rawfile/";
final String local = "/local/";
Uri requestUri = request.getRequestUrl();
if (authority.equals(requestUri.getDecodedAuthority())) {
String path = requestUri.getDecodedPath();
if (TextTool.isNullOrEmpty(path)) {
return super.processResourceRequest(webView, request);
}
if (path.startsWith(rawFile)) {
// 根據自定義規則訪問資源文件
String rawFilePath = "entry/resources/rawfile/" + path.replace(rawFile, "");
String mimeType = URLConnection.guessContentTypeFromName(rawFilePath);
try {
Resource resource = getResourceManager().getRawFileEntry(rawFilePath).openRawFile();
ResourceResponse response = new ResourceResponse(mimeType, resource, null);
return response;
} catch (IOException e) {
HiLog.info(TAG, "open raw file failed");
}
}
if (path.startsWith(local)) {
// 根據自定義規則訪問本地文件
String localFile = getContext().getFilesDir() + path.replace(local, "/");
HiLog.info(TAG, "open local file " + localFile);
File file = new File(localFile);
if (!file.exists()) {
HiLog.info(TAG, "file not exists");
return super.processResourceRequest(webView, request);
}
String mimeType = URLConnection.guessContentTypeFromName(localFile);
try {
InputStream inputStream = new FileInputStream(file);
ResourceResponse response = new ResourceResponse(mimeType, inputStream, null);
return response;
} catch (IOException e) {
HiLog.info(TAG, "open local file failed");
}
}
}
return super.processResourceRequest(webView, request);
}
});
2、加載資源文件或本地文件。
// 加載資源文件 resources/rawfile/example.html
webView.load("https://example.com/rawfile/example.html");
// 加載本地文件 /data/data/com.example.dataability/files/example.html
webView.load("https://example.com/local/example.html");
方式二:通過Data Ability訪問文件
1、創建Data Ability。
public class ExampleDataAbility extends Ability {
private static final String PLACEHOLDER_RAW_FILE = "/rawfile/";
private static final String PLACEHOLDER_LOCAL_FILE = "/local/";
private static final String ENTRY_PATH_PREFIX = "entry/resources";
@Override
public RawFileDescriptor openRawFile(Uri uri, String mode) throws FileNotFoundException {
final int splitChar = '/';
if (uri == null) {
throw new FileNotFoundException("Invalid Uri");
}
// path will be like /com.example.dataability/rawfile/example.html
String path = uri.getEncodedPath();
final int splitIndex = path.indexOf(splitChar, 1);
if (splitIndex < 0) {
throw new FileNotFoundException("Invalid Uri " + uri);
}
String targetPath = path.substring(splitIndex);
if (targetPath.startsWith(PLACEHOLDER_RAW_FILE)) {
// 根據自定義規則訪問資源文件
try {
return getResourceManager().getRawFileEntry(ENTRY_PATH_PREFIX + targetPath).openRawFileDescriptor();
} catch (IOException e) {
throw new FileNotFoundException("Not found support raw file at " + uri);
}
} else if (targetPath.startsWith(PLACEHOLDER_LOCAL_FILE)) {
// 根據自定義規則訪問本地文件
File file = new File(getContext().getFilesDir(), targetPath.replace(PLACEHOLDER_LOCAL_FILE, ""));
if (!file.exists()) {
throw new FileNotFoundException("Not found support local file at " + uri);
}
return getRawFileDescriptor(file, uri);
} else {
throw new FileNotFoundException("Not found support file at " + uri);
}
}
private RawFileDescriptor getRawFileDescriptor(File file, Uri uri) throws FileNotFoundException {
try {
final FileDescriptor fileDescriptor = new FileInputStream(file).getFD();
return new RawFileDescriptor() {
@Override
public FileDescriptor getFileDescriptor() {
return fileDescriptor;
}
@Override
public long getFileSize() {
return -1;
}
@Override
public long getStartPosition() {
return 0;
}
@Override
public void close() throws IOException {
}
};
} catch (IOException e) {
throw new FileNotFoundException("Not found support local file at " + uri);
}
}
}
2、在config.json中注冊Data Ability。
{
"name": "com.example.webview.ExampleDataAbility",
"type": "data",
"uri": "dataability://com.example.dataability",
"metaData": {
"customizeData": [
{
"name": "com.example.provider",
"extra": "$profile:path"
}
]
}
}
以及在resources/base/profile目錄新增path.xml:
<paths>
<root-path name="root" path="/" />
</paths>
3、配置支持訪問Data Ability資源。
webConfig.setDataAbilityPermit(true);
4、通過dataability協議加載資源文件或本地文件。
// 加載資源文件 resources/rawfile/example.html
webView.load("dataability://com.example.dataability/rawfile/example.html");
// 加載本地文件 /data/data/com.example.dataability/files/example.html
webView.load("dataability://com.example.dataability/local/example.html");
更多內容:
1、社區:鴻蒙巴士https://www.harmonybus.net/
2、公眾號:HarmonyBus
3、技術交流QQ群:714518656