鸿蒙开源组件——OHOS WebView 和 Javascript 双向交互框架

jacksky
发布于 2021-10-13 17:53
浏览
1收藏

JsBridge

项目介绍

  • 功能: 轻量可扩展 OHOS WebView 和 Javascript 双向交互框架。鸿蒙开源组件——OHOS WebView 和 Javascript 双向交互框架-鸿蒙开发者社区

    安装教程

    方式一

    1. 将debugkit模块内容拷贝到自己项目对应模块目录下
    2. 在需要使用的模块的build.gradle中引入

 

dependencies {
    compile project(path: ':jsbridge')
}

 

在sdk5,DevEco Studio2.1 Release下项目可直接运行

方式二

在project的build.gradle中添加mavenCentral()的引用

repositories {   
 	...   
 	mavenCentral()   
	 ...           
 }

在entry的build.gradle中添加依赖

dependencies { 
... 
implementation 'com.gitee.archermind-ti:jsbridge-ohos:1.0.0-beta2' 
implementation 'org.json:json:20090211'
... 
}

使用说明

我们以 JS 调用原生模块来实现 ajax 跨域请求来简单介绍下库的使用

1.创建模块

创建模块需要继承 JsModule 并实现getModuleName 方法, 模块命名要求和 java 变量命名一致, 不允许为空, 只允许 下划线(_) 字母 和数字, 如果是静态模块(不包含模块名),需要继承JsStaticModule, 下面创建了一个 Native 模块

 

public class NativeModule extends JsModule {
@Override
public String getModuleName() {
    return "native";
}}

2.创建调用方法

Module 里面创建方法需要使用注解@JSBridgeMethod, 默认情况下 Java 方法名就是 JS 调用的方法名, 也可以通过@JSBridgeMethod(methodName = "xx")来指定调用方法名。方法要求不能为 static 或者 abstract, 可以包含返回类型,如果返回类型是对象默认转为 String 后返回给 JS, 方法的参数要求为以下类型,可以直接映射到它们对应的JS类型

Java 类型 映射的 JS 类型
Boolean / boolean Bool
Integer/ int Number
Float / float Number
Double / double Number
Long / long Number
String String
JBCallback function
JBMap Object
JBArray Array

为了 JS 更方便调用, 我们把方法参数定义成ajax一样, 我们先看下 ajax 请求结构

$.ajax({

	type:'GET',
	url:'xxx.com',
	dataType:'text'
	data:{a:1, b:'xx'},
	success:function(data){
	},
	error:function(err){
	}
})

必须要添加@JSBridgeMethod注解,参数是JBMap 映射到 JS 的对象

JBCallback.apply用来回调 JS 的回调方法,不定参数,支持 Java 基本类型,数组(WritableJBArray),和 对象(WritableJBMap), 如果为其他对象,默认转为 string转递给 JS

3.注册 Module 有两种方式可以注册 module, 默认注册, 动态注册

JsBridgeConfig.getSetting().registerDefaultModule(NativeModule.class);

// 或者

JsBridge.loadModule(NativeModule.class) JsBridgeConfig 配置下如下:

方法 类型 描述 默认
setProtocol string JS调用的对象名 JsBridge
setLoadReadyMethod string 加载完成回调函数 onJsBridgeReady
registerDefaultModule JsModule 公用模块, 默认加载
debugMode bool 调试模式下输出TAG 为JsBridgeDebug 的日志 false

4.WebView 注入方法 & 设置回调

public class WebViewAbility extends BaseAbility {

   private JsBridge jsBridge;

    @Override
   public void onStart(Intent intent) {

       jsBridge = JsBridge.loadModule();
        WebView webView = (WebView) findComponentById(ResourceTable.Id_webview);
        
         webView.setBrowserAgent(new BrowserAgent(this) {
            
                   @Override
                   public boolean onJsTextInput(WebView webView, String url, String message, String defaultInput, JsTextInputResult result) {
      
                       if (jsBridge.callJsPrompt(message, result)) {
                           return true;
                       }
                       return super.onJsTextInput(webView, url, message, defaultInput, result);
                   }
       
               });
       
        webView.setWebAgent(new WebAgent() {
       
                   @Override
                   public void onPageLoaded(WebView webView, String url) {
                       super.onPageLoaded(webView, url);
                       // 页面加载结束后自定义处理
                       jsBridge.injectJs(getAbility(),webView);
                   }
               });
      
           }
   }

    @Override
    public void terminateAbility() {
        jsBridge.release();
        super.terminateAbility();
    
    }
}

 

现在,在 JS 代码中可以这样调用这个方法:

JsBridge.native.ajax({

	type:'GET',
	url:'xxx.com',
	dataType:'text'
	data:{a:1, b:'xx'},
	success:function(data){
	},
	error:function(err){
	}
})

如果想直接JsBridge.ajax, 把父类从JsModule 改成 JsStaticModule就好了

还有一个问题值得注意,因为 JS 执行是异步的,为了确保注入 JS 已经完成,请在回调里执行方法,或者判断 JsBridge 对象存在

window.onJsBridgeReady = function () {

    JsBridge.native.ajax({...});
}

// 或者

document.addEventListener('onJsBridgeReady', function(){

    JsBridge.native.ajax({...});
})

// 或者

if (JsBridge) {

	JsBridge.native.ajax({...});
}

更多的文档和示例请参考sample

版本迭代

  • v1.0.0

基线release版本

Releases v2.1.0

commit id af7f491e1c081cd1be5646fb200c1a0eacbe8e24

版权和许可信息

Copyright pengwei1024

Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at

http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License.

jsbridge-master.zip 358.77K 62次下载
已于2021-10-13 17:53:38修改
收藏 1
回复
举报
回复
    相关推荐