HarmonyOS 鸿蒙Next web 桥接原生代码方法

发布于 1周前 作者 ionicwang 来自 鸿蒙OS

HarmonyOS 鸿蒙Next web 桥接原生代码方法 web 桥接原生代码方法

2 回复

// pluginPage.ets:

import { Logger } from ‘@hw-agconnect/hmcore’; import router from ‘@ohos.router’; import web_webview from ‘@ohos.web.webview’; import { BusinessError } from ‘@kit.BasicServicesKit’; import webview from ‘@ohos.web.webview’; import buffer from ‘@ohos.buffer’; import { util } from ‘@kit.ArkTS’; import { common } from ‘@kit.AbilityKit’;

const TAG = ‘[PluginPage]’

interface UrlParams { url: string; methodList: Array<string> }

class testClass { constructor() { }

GreeApp(cls:string): void { let obj:ESObject = JSON.parse(cls); let clsName:string = obj.clsName; let func:string = obj.funName; let funData:object = obj.funData; let funCallback:string = obj.funCallback let path:string = ../apis/${clsName}; Logger.info(TAG, "clsName = "+cls); import(path).then((ns: ESObject) => { let sys: ESObject = new nsclsName; sysfunc; }) .catch((err:BusinessError) => { console.log(‘err12344:’+err) }) // {“clsName”:“System”,“funName”:“getSystemInfo”,“funData”:{}, // “funCallback”:“GreeApp_cb_1720515357602.0.7082100644892653”} }

getInfo(param:ESObject) { console.log(‘getInfo111:’+JSON.stringify(param)) let str:string=param.arguments[0]; let callback:string=param.callback; let controller=AppStorage.get(‘controller’) as WebviewController; controller.runJavaScript(pluginsInterfaceCallBack1("${callback}",'{"timezoneOffset":"+8","mainMac":"","subdivCode":"","host":"","fullstatueJson":"","name":"qw"}'))

}

finishLoad() { Logger.info(TAG, “finishLoad”) }

onCallBack() { Logger.info(TAG, "onCallBack = "); }

sendDataToDevice(){

} }

@Entry({ routeName: ‘PluginPage’ }) @Component export struct PluginPage { controller: WebviewController = new web_webview.WebviewController() @State url: string = ‘’; @State testObj: testClass = new testClass(); methodList: Array<string> = (router.getParams() as UrlParams).methodList; @State jsContent:string=’’; private context=getContext(this) as common.UIAbilityContext; ports: webview.WebMessagePort[] = []; webviewJavascriptBridge = “(function(){if(window.WebViewJavascriptBridge){return}var receiveMessageQueue=[];var messageHandlers={};var responseCallbacks={};var uniqueId=1;function init(messageHandler){if(WebViewJavascriptBridge._messageHandler){throw new Error(‘WebViewJavascriptBridge.init called twice’);}WebViewJavascriptBridge._messageHandler=messageHandler;var receivedMessages=receiveMessageQueue;receiveMessageQueue=null;for(var i=0;i<receivedMessages.length;i++){_dispatchMessageFromNative(receivedMessages[i])}}function send(data,responseCallback){_doSend(‘jsbridge’,‘send’,data,responseCallback)}function registerHandler(handlerName,handler){messageHandlers[handlerName]=handler}function callHandler(handlerName,data,responseCallback){_doSend(‘jsbridge’,handlerName,data,responseCallback)}function callHandlerWithModule(moduleName,handlerName,data,responseCallback){doSend(moduleName,handlerName,data,responseCallback)}function doSend(moduleName,handlerName,message,responseCallback){var callbackId;if(typeof responseCallback===‘string’){callbackId=responseCallback}else if(responseCallback){callbackId='cb’+(uniqueId++)+’’+new Date().getTime();responseCallbacks[callbackId]=responseCallback}else{callbackId=’’}try{var evalStr1=‘window.’+moduleName+’.’;if(moduleName==‘jsbridge’&&handlerName!=‘response’){evalStr1+=‘handler’}else{evalStr1+=handlerName}var fn=eval(evalStr1)}catch(e){console.log(e)}if(typeof fn===‘function’){var evalStr=‘window.’+moduleName;var fnwindow=eval(evalStr);var responseData;if(moduleName==‘jsbridge’&&handlerName!=‘response’){responseData=fn.call(fnwindow,handlerName,JSON.stringify(message),callbackId)}else{responseData=fn.call(fnwindow,JSON.stringify(message),callbackId)}if(responseData){responseCallback=responseCallbacks[callbackId];if(!responseCallback){return}responseCallback(responseData);delete responseCallbacks[callbackId]}}}function _dispatchMessageFromNative(messageJSON){setTimeout(function(){var message=JSON.parse(messageJSON);var responseCallback;if(message.responseId){responseCallback=responseCallbacks[message.responseId];if(!responseCallback){return}responseCallback(message.responseData);delete responseCallbacks[message.responseId]}else{if(message.callbackId){var callbackResponseId=message.callbackId;responseCallback=function(responseData){_doSend(‘jsbridge’,‘response’,responseData,callbackResponseId)}}var handler=WebViewJavascriptBridge._messageHandler;if(message.handlerName){handler=messageHandlers[message.handlerName]}try{handler(message.data,responseCallback)}catch(exception){if(typeof console!=‘undefined’){console.log(“WebViewJavascriptBridge: WARNING: javascript handler threw.”,message,exception)}}}})}function _handleMessageFromNative(messageJSON){if(receiveMessageQueue){receiveMessageQueue.push(messageJSON)}_dispatchMessageFromNative(messageJSON)}var WebViewJavascriptBridge=window.WebViewJavascriptBridge={init:init,send:send,registerHandler:registerHandler,callHandler:callHandler,callHandlerWithModule:callHandlerWithModule,_handleMessageFromNative:_handleMessageFromNative};console.log(“start jsbridge …”);var doc=document;var readyEvent=doc.createEvent(‘Events’);readyEvent.initEvent(‘WebViewJavascriptBridgeReady’);readyEvent.bridge=WebViewJavascriptBridge;doc.dispatchEvent(readyEvent);console.log(“end jsbridge …”)})();”;

aboutToAppear(){ web_webview.WebviewController.setWebDebuggingAccess(true); const params = router.getParams() as UrlParams; this.url = params.url + ‘?mac=9424b8a49d7a&data=[3,0,1,1,0,0,0,28,0,0,1,0,0,0,1,“7e000035”,1,0,0,5,0,65,0,0,0,0,0,0]&functype=0&mainMac=&vender=7e000035’; }

build() { Column() { Web({ src: this.url, controller: this.controller })// 将对象注入到web端 .javaScriptProxy({ object: this.testObj, name: “gree”, methodList: [‘onCallBack’,“GreeApp”, ‘getInfo’, ‘PluginInterface’, ‘sendDataToDevice’,“getSystemInfo”,‘finishLoad’], controller: this.controller }) .domStorageAccess(true)

    .onPageEnd((event) => {
      // 推荐在此事件中执行JavaScript脚本
      Logger.info(TAG, 'onPageEnd');
      if (event) {
        Logger.info(TAG, 'onPageEnd url:' + event.url);
      }
      getContext(this).resourceManager.getRawFileContent('WebViewJavascriptBridge.js', (err, data) => {
        const str = buffer.from(data.buffer).toString()
        this.controller.runJavaScript(str);
        this.controller.runJavaScript(`document.dispatchEvent(new Event('deviceready'))`)
        AppStorage.setOrCreate('controller', this.controller);
        console.log('controller1111:' + JSON.stringify(this.controller))
      })

    })
    .javaScriptAccess(true)
}

}

createWebMessagePorts() { try { // 1、创建两个消息端口。 this.ports = this.controller.createWebMessagePorts(); this.ports.forEach((port, index) => { Logger.info(TAG, 'index = '+ index); Logger.info(TAG, 'port = '+ JSON.stringify(port)); }) if (this.ports && this.ports[1]) { Logger.info(TAG, ‘ports存在’); } else { Logger.info(TAG, ports is null, Please initialize first); } // 2、在应用侧的消息端口(如端口1)上注册回调事件。 this.ports[0].onMessageEvent((result: webview.WebMessage) => { Logger.info(TAG, ‘在应用侧的消息端口(如端口1)上注册回调事件’); let msg = ‘Got msg from HTML:’; if (typeof (result) === ‘string’) { Logger.info(TAG, received string message from html5, string is: ${result}); msg = msg + result; } else if (typeof (result) === ‘object’) { if (result instanceof ArrayBuffer) { Logger.info(TAG, received arraybuffer from html5, length is: ${result.byteLength}); msg = msg + 'lenght is '+ result.byteLength; } else { Logger.info(TAG, ‘not support’); } } else { Logger.info(TAG, ‘not support’); } // this.receivedFromHtml = msg; }) // 3、将另一个消息端口(如端口0)发送到HTML侧,由HTML侧保存并使用。 this.controller.postMessage(‘init_port’, [this.ports[0]], ‘*’); } catch (error) { Logger.info(TAG, ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}); } } }

更多关于HarmonyOS 鸿蒙Next web 桥接原生代码方法的实战系列教程也可以访问 https://www.itying.com/category-93-b0.html


HarmonyOS(鸿蒙)Next web 桥接原生代码的方法主要通过以下步骤实现:

在HarmonyOS开发中,若需将Web技术与原生代码进行桥接,通常依赖于鸿蒙系统提供的特定API和框架。开发者可以利用这些工具,在Web端与原生端之间建立通信机制。

具体实现时,首先需在原生代码中定义桥接接口,这些接口负责接收来自Web端的请求并调用相应的原生功能。接着,在Web端通过JavaScript调用这些预定义的接口。为实现这一点,鸿蒙系统可能提供了一些特定的JavaScript库或API,允许Web代码与原生代码进行交互。

此外,还需注意数据格式的统一和通信的安全性。确保Web端与原生端之间的数据传输格式一致,同时采取必要的安全措施,防止数据泄露或恶意攻击。

在开发过程中,可能会遇到权限管理、性能优化等问题。开发者需根据鸿蒙系统的规范,合理申请和管理权限,同时关注性能瓶颈,进行必要的优化。

如果问题依旧没法解决请联系官网客服,官网地址是:https://www.itying.com/category-93-b0.html 。在这里,你可以获得更专业的技术支持和解决方案。

回到顶部