Fa应用是支持WebView嵌入H5网页的,WebView提供在应用中集成Web页面的能力,不过目前只支持Java模板的WebView。

WebView的使用方法

WebView派生于通用组件Component,可以像普通组件一样进行使用。

方式一:

在layout目录下的xml文件中创建WebView。

ohos:id="$+id:webview"

ohos:height="match_parent"

ohos:width="match_parent">

2.在MainAbility.java文件中,使用load方法加载Web页面。

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

webView.getWebConfig() .setJavaScriptPermit(true); // 如果网页需要使用JavaScript,增加此行;如何使用JavaScript下文有详细介绍

final String url = EXAMPLE_URL; // EXAMPLE_URL由开发者自定义

webView.load(url);

方式二:

1.在ComponentContainer中创建WebView。

WebView webView = new WebView(getContext());

webView.setWidth(ComponentContainer.LayoutConfig.MATCH_PARENT);

webView.setHeight(ComponentContainer.LayoutConfig.MATCH_PARENT);

webView.getWebConfig() .setJavaScriptPermit(true); // 如果网页需要使用JavaScript,增加此行;如何使用JavaScript下文有详细介绍

addComponent(webView);

2.加载Web页面。

final String url = EXAMPLE_URL; // EXAMPLE_URL由开发者自定义

webView.load(url);

定制网址加载行为

当Web页面进行链接跳转时,WebView默认会打开目标网址,通过以下方式可以定制该行为。

自定义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());

浏览网页历史记录

通过getNavigator方法获取Navigator对象。

Navigator navigator = webView.getNavigator();

2.使用canGoBack()或canGoForward()检查是否可以向后或向前浏览,使用goBack()或goForward()向后或向前浏览。

if (navigator.canGoBack()) {

navigator.goBack();

}

if (navigator.canGoForward()) {

navigator.goForward();

}

使用JavaScript

通过以下方式,可以建立应用和页面间的JavaScript调用。

通过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() {

@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方法访问文件

通过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:

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");

Logo

为开发者提供学习成长、分享交流、生态实践、资源工具等服务,帮助开发者快速成长。

更多推荐