鸿蒙webview的使用
config.json下面的module中添加以下内容
"metaData": {
"customizeData": [
{
"name": "hwc-theme",
"value": "androidhwext:style/Theme.Emui.Light.NoTitleBar"
}
]
},
config.json下面的module中添加以下内容
"reqPermissions": [
{
"name": "ohos.permission.INTERNET" //网络访问权限
},
{
"name": "ohos.permission.WRITE_USER_STORAGE" //写文件权限
},
{
"name": "ohos.permission.READ_USER_STORAGE" //读文件权限
}
]
通过Java回调模拟localStorage
鸿蒙的webview不支持localStorage
鸿蒙支持Java回调处理js请求,方式如下:
js中:
if(window.JavaCallBack && window.JavaCallBack) {
window.JavaCallBack.call("回调参数")
}
Java中:
webview.addJsCallback("JavaCallBack ", str -> {
// 处理接收到的Js发送来的消息
});
其中webview为鸿蒙webview组件的实例
鸿蒙同样支持Java代码唤起js,不赘述
以下为模拟localStorage的详细代码:
webview.addJsCallback("GetSession", str - >{
// 处理接收到的Js发送来的消息
File file = new File(getFilesDir(), Uri.parse("dataability:///com.lccbjc.blog?session.txt").getDecodedQuery());
return getText(file);
});
webview.addJsCallback("SaveSession", str - >{
File file = new File(getFilesDir(), Uri.parse("dataability:///com.lccbjc.blog?session.txt").getDecodedQuery());
FileOutputStream fileOutputStream = null;
try {
fileOutputStream = new FileOutputStream(file);
} catch(FileNotFoundException e) {
e.printStackTrace();
}
try {
fileOutputStream.write(str.getBytes());
} catch(IOException e) {
e.printStackTrace();
}
// 返回给Js
return "Save Session Success";
});
private String getText(File fileDescriptor) {
try (FileInputStream fileInputStream = new FileInputStream(fileDescriptor);
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(fileInputStream))) {
String line;
StringBuilder stringBuilder = new StringBuilder();
while ((line = bufferedReader.readLine()) != null) {
stringBuilder.append(line);
}
return stringBuilder.toString();
} catch(IOException ioException) {
HiLog.error(LABEL_LOG, "%{public}s", "showText: ioException");
}
return null;
}
Uri格式:Scheme://[authority]/
-
Scheme: 协议方案名
-
authority: 设备ID
-
path: 资源路径
-
query: 查询参数,本文用到的地方可理解为文件名
-
fragment: 指示要访问的子资源
输入法遮挡页面内容的问题
在相应的AblitySlice中使用以下方法
getWindow().setInputPanelDisplayType(WindowManager.LayoutConfig.INPUT_ADJUST_PAN);
webview处理alert
webview.setBrowserAgent(new BrowserAgent(this) {
webview的使用
WebView webview = (WebView) findComponentById(ResourceTable.Id_webview);
WebConfig webConfig = webview.getWebConfig();
// 是否支持Javascript,默认值false
webConfig.setJavaScriptPermit(true);
webview.load(URL);
自定义跳转url事件
webview.setWebAgent(new WebAgent() {
@Override
public boolean isNeedLoadUrl(WebView webView, ResourceRequest request) {
if (request.getRequestUrl() == 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);
}
}
});