赞
踩
{
...
"module": {
...
"reqPermissions": [
{
"name": "ohos.permission.INTERNET"
}
],
...
}
}
<ohos.agp.components.webengine.WebView
ohos:id="$+id:webview"
ohos:height="match_parent"
ohos:width="match_parent">
</ohos.agp.components.webengine.WebView>
WebView webView = (WebView) findComponentById(ResourceTable.Id_webview);
webView.getWebConfig().setJavaScriptPermit(true); // 如果网页需要使用JavaScript,增加此行;如何使用JavaScript下文有详细介绍
final String url = EXAMPLE_URL; // EXAMPLE_URL由开发者自定义
webView.load(url);
DirectionalLayout dLayout = new DirectionalLayout(this);
dLayout.setLayoutConfig(new ComponentContainer.LayoutConfig(
ComponentContainer.LayoutConfig.MATCH_PARENT,
ComponentContainer.LayoutConfig.MATCH_PARENT
));
super.setUIContent(dLayout);
WebView webView = new WebView(getContext());
webView.setWidth(ComponentContainer.LayoutConfig.MATCH_PARENT);
webView.setHeight(ComponentContainer.LayoutConfig.MATCH_PARENT);
webView.getWebConfig().setJavaScriptPermit(true); // 如果网页需要使用JavaScript,增加此行;如何使用JavaScript下文有详细介绍
dLayout.addComponent(webView);
final String url = EXAMPLE_URL; // EXAMPLE_URL由开发者自定义
webView.load(url);
Navigator navigator = webView.getNavigator();
if (navigator.canGoBack()) {
navigator.goBack();
}
if (navigator.canGoForward()) {
navigator.goForward();
}
webView.getWebConfig().setJavaScriptPermit(true);
final String jsName = "JsCallbackToApp";
webView.addJsCallback(jsName, new JsCallback() {
@Override
public String onCallback(String msg) {
// 增加自定义处理
return "jsResult";
}
});
function callToApp() {
if (window.JsCallbackToApp && window.JsCallbackToApp.call) {
var result = JsCallbackToApp.call("message from web");
}
}
webView.executeJs("javascript:callFuncInWeb()", new AsyncCallback<String>() {
@Override
public void onReceive(String msg) {
// 在此确认返回结果
}
});
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); // 发生错误时自定义处理 } });
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);
// 加载进度变更时自定义处理
}
});
private class ExampleWebAgent extends WebAgent { public static final String EXAMPLE_URL = "..."; @Override public boolean isNeedLoadUrl(WebView webview, ResourceRequest request) { if (request == null || request.getRequestUrl() == null) { return false; } Uri uri = request.getRequestUrl(); // EXAMPLE_URL由开发者自定义 if (uri.getDecodedHost().equals(EXAMPLE_URL)) { // 增加开发者自定义逻辑 return false; } else { return super.isNeedLoadUrl(webview, request); } } }
webView.setWebAgent(new ExampleWebAgent());
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); } });
// 加载资源文件 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");
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); } } }
{
"name": "com.example.webview.ExampleDataAbility",
"type": "data",
"uri": "dataability://com.example.dataability",
"metaData": {
"customizeData": [
{
"name": "com.example.provider",
"extra": "$profile:path"
}
]
}
}
<paths>
<root-path name="root" path="/" />
</paths>
webConfig.setDataAbilityPermit(true);
// 加载资源文件 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");
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。