ARTICLE DETAIL

资讯详情

深耕网站建设与运营推广的一线实战洞察。

鸿蒙项目实战(十):web和js交互

鸿蒙项目实战(十):web和js交互

1、实现android的addJavascriptInterface操作

即鸿蒙注入JavaScript对象到window对象中

javaScriptProxy

javaScriptProxy(javaScriptProxy: JavaScriptProxy) 

// xxx.ets
import { webview } from '@kit.ArkWeb';class TestObj {constructor() {}test(data1: string, data2: string, data3: string): string {console.log("data1:" + data1);console.log("data2:" + data2);console.log("data3:" + data3);return "AceString";}asyncTest(data: string): void {console.log("async data:" + data);}toString(): void {console.log('toString' + "interface instead.");}
}@Entry
@Component
struct WebComponent {controller: webview.WebviewController = new webview.WebviewController();testObj = new TestObj();build() {Column() {Button('deleteJavaScriptRegister').onClick(() => {try {this.controller.deleteJavaScriptRegister("objName");} catch (error) {console.error(`ErrorCode: ${(error as BusinessError).code},  Message: ${(error as BusinessError).message}`);}})Web({ src: 'www.example.com', controller: this.controller }).javaScriptAccess(true).javaScriptProxy({object: this.testObj,name: "objName",methodList: ["test", "toString"],asyncMethodList: ["asyncTest"],controller: this.controller,})}}
}

 

2、runJavaScriptExt

执行JavaScript脚本,并通过回调方式返回脚本执行的结果

Web().onPageEnd(async () => {// 执行js方法this.controller.runJavaScriptExt("javascript:window.addEventListener('downFile',function(e){control.downLoadExportFile(JSON.stringify(e.detail))})").then((result) =>{LogUtil.info("返回的result"+JSON.stringify(result));})

 

 

返回列表