鸿蒙JSFA 使用 WebView
开始之前我抛出一个问题:为什么鸿蒙有JS UI和元服务为啥还需要webview呢?
1.JSFA
demo.html
<div class="container"> <list class="todo-wraper"> <list-item class="todo-item" @click="openWebView"> <text class="todo-title">WebView</text> <text class="todo-section">WebView测试</text> </list-item> </list> </div>
demo.js
export const AboutAbility = { openWebView: async function(){ var actionData = {}; var action = {}; action.bundleName = 'com.example.phone'; action.abilityName = 'com.example.phone.ability.AboutAbility'; action.messageCode = 1001; action.data = actionData; action.abilityType = 0; action.syncOption = 0; var result = await FeatureAbility.callAbility(action); var ret = JSON.parse(result); if (ret.code == 0) { console.log(ret); } else { console.error(JSON.stringify(ret.code)); } }, } export default { data: { title: 'World' }, async openWebView(){ AboutAbility.openWebView(); } }
2.JAVAPA
AboutAbility.java
package com.example.phone.ability; import ohos.aafwk.ability.Ability; import ohos.aafwk.content.Intent; import ohos.aafwk.content.Operation; import ohos.app.Context; import ohos.rpc.*; import ohos.hiviewdfx.HiLog; import ohos.hiviewdfx.HiLogLabel; import java.io.OutputStream; import java.net.Socket; public class AboutAbility extends Ability { private static final int OPEN_WEBVIEW = 1001; private AboutAbility.AboutRemote aboutRemote; @Override public IRemoteObject onConnect(Intent intent) { Context context = getContext(); aboutRemote = new AboutAbility.AboutRemote(context); return aboutRemote.asObject(); } class AboutRemote extends RemoteObject implements IRemoteBroker { private Context context; private Socket socket = null; private OutputStream os = null; public AboutRemote(Context context) { super("AboutRemote"); this.context = context; } @Override public boolean onRemoteRequest(int code, MessageParcel data, MessageParcel reply, MessageOption option) throws RemoteException { switch (code) { case OPEN_WEBVIEW:{ System.out.println("开启webview"); //主要代码 Intent intent = new Intent(); Operation operation = new Intent.OperationBuilder().withBundleName(getBundleName()) .withAbilityName(WebViewAbility.class.getName()).build(); intent.setOperation(operation); startAbility(intent); //主要代码 break; } default: { reply.writeString("service not defined"); return false; } } return true; } @Override public IRemoteObject asObject() { return this; } } }
3.JAVAFA
官方WebView文档:https://developer.harmonyos.com/cn/docs/documentation/doc-guides/ui-java-component-webview-0000001092715158
web_view.xml
<?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:orientation="vertical"> <ohos.agp.components.webengine.WebView ohos:id="$+id:webview" ohos:height="match_parent" ohos:width="match_parent"> </ohos.agp.components.webengine.WebView> </DirectionalLayout>
WebViewAbility.java
public class WebViewAbility extends Ability { private static final HiLogLabel LABEL_LOG = new HiLogLabel(3, 0xD001100, "Demo"); @Override public void onStart(Intent intent) { super.onStart(intent); System.out.println("WEBVIEW start"); super.setMainRoute(WebViewAbilitySlice.class.getName()); } }
WebViewAbilitySlice.java
public class WebViewAbilitySlice extends AbilitySlice { @Override public void onStart(Intent intent) { super.onStart(intent); // 加载XML布局作为根布局 super.setUIContent(ResourceTable.Layout_web_view); WebView webView = (WebView) findComponentById(ResourceTable.Id_webview); final String url = "https://m.bilibili.com/"; // EXAMPLE_URL由开发者自定义 webView.getWebConfig().setJavaScriptPermit(true);// 启动JS webView.load(url); } }
4.配置
打开config.json
securityConfig
"securityConfig": { "domainSettings": { "cleartextPermitted": true, "domains": [ { "subDomains": true, "name": "m.bilibili.com" } ] } }
abilities
{ "skills": [ { "entities": [ "entity.system.home" ], "actions": [ "action.system.home" ] } ], "name": "com.example.phone.MainAbility", "icon": "$media:icon", "description": "$string:mainability_description", "label": "XXXXX", "type": "page", "launchType": "standard" },
{ "skills": [ { "entities": [ ], "actions": [ "action.ability.webview" ] } ], "orientation": "portrait", "formEnabled": false, "name": "com.example.phone.ability.WebViewAbility", "icon": "$media:icon", "description": "$string:mainability_description", "label": "webview", "type": "page", "launchType": "standard" },
权限
ohos.permission.INTERNET
5.Java FA调用WebView 函数
WebViewAbilitySlice.java
通过调用JS函数来隐藏B站LOGO
// 页面运行情况 webView.setWebAgent(new WebAgent() { @Override public void onPageLoaded(WebView webView, String url) { super.onPageLoaded(webView, url); // 页面加载结束后自定义处理 System.out.println("页面加载完毕"); // iconfont Navbar_logo webView.executeJs("document.getElementsByClassName(\"iconfont Navbar_logo\")[0].style.display = \"none\"", new AsyncCallback<String>() { @Override public void onReceive(String msg) { System.out.println("AsyncCallback:"+msg); // 在此确认返回结果 } }); } });
6.页面加载进度条
WebViewAbilitySlice.java