鸿蒙JSFA 使用 WebView 原创

卡哇伊大喵
发布于 2021-4-20 18:09
浏览
2收藏

鸿蒙JSFA 使用 WebView
我的具体流程:JSFA 调用 JAVAPA 拉起 JAVAFA

开始之前我抛出一个问题:为什么鸿蒙有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

鸿蒙JSFA 使用 WebView-开源基础软件社区

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);
                        // 在此确认返回结果
                    }
                });
            }
        });

鸿蒙JSFA 使用 WebView-开源基础软件社区

©著作权归作者所有,如需转载,请注明出处,否则将追究法律责任
8
收藏 2
回复
举报
6条回复
按时间正序
/
按时间倒序
执剑天涯奈我何
执剑天涯奈我何

 webView.getWebConfig().setJavaScriptPermit(true);// 启动JS

这块为什么要启动js

1
回复
2021-6-4 12:04:00
丨张明亮丨
丨张明亮丨 回复了 执剑天涯奈我何
webView.getWebConfig().setJavaScriptPermit(true);// 启动JS 这块为什么要启动js

意思是要支持JavaScript,现在大部分网站都是需要JavaScript的

回复
2021-6-25 09:35:59
一朵浪花呀
一朵浪花呀

非常不错 ,刚想问来着

回复
2021-6-25 11:37:47
一朵浪花呀
一朵浪花呀

请问下这块在手表上有测试过么

回复
2021-6-25 11:48:32
卡哇伊大喵
卡哇伊大喵 回复了 执剑天涯奈我何
webView.getWebConfig().setJavaScriptPermit(true);// 启动JS 这块为什么要启动js

启动JS才能执行JS脚本

回复
2021-6-25 15:36:47
卡哇伊大喵
卡哇伊大喵 回复了 一朵浪花呀
请问下这块在手表上有测试过么

我没手表,手表上估计没有webview

回复
2021-6-25 15:37:07
回复
添加资源
添加资源将有机会获得更多曝光,你也可以直接关联已上传资源 去关联
    相关推荐