鸿蒙NEXT版实战开发:前端页面调用应用侧函数(前端页面JavaScript) ...

瑞星  金牌会员 | 2024-11-2 17:43:47 | 显示全部楼层 | 阅读模式
打印 上一主题 下一主题

主题 987|帖子 987|积分 2961

往期鸿蒙全套实战出色文章必看内容:



  • 鸿蒙开发核心知识点,看这篇文章就够了
  • 最新版!鸿蒙HarmonyOS Next应用开发实战学习门路
  • 鸿蒙HarmonyOS NEXT开发技能最全学习门路指南
  • 鸿蒙应用开发实战项目,看这一篇文章就够了(部分项目附源码)

前端页面调用应用侧函数

开发者使用Web组件将应用侧代码注册到前端页面中,注册完成之后,前端页面中使用注册的对象名称就可以调用应用侧的函数,实现在前端页面中调用应用侧方法。
注册应用侧代码有两种方式,一种在Web组件初始化调用,使用javaScriptProxy()接口。别的一种在Web组件初始化完成后调用,使用registerJavaScriptProxy()接口。
在下面的示例中,将test()方法注册在前端页面中, 该函数可以在前端页面触发运行。


  • javaScriptProxy()接口使用示例如下。
    1. // xxx.ets
    2. import { webview } from '@kit.ArkWeb';
    3. class testClass {
    4.   constructor() {
    5.   }
    6.   test(): string {
    7.     return 'ArkTS Hello World!';
    8.   }
    9. }
    10. @Entry
    11. @Component
    12. struct WebComponent {
    13.   webviewController: webview.WebviewController = new webview.WebviewController();
    14.   // 声明需要注册的对象
    15.   @State testObj: testClass = new testClass();
    16.   build() {
    17.     Column() {
    18.       // Web组件加载本地index.html页面
    19.       Web({ src: $rawfile('index.html'), controller: this.webviewController})
    20.         // 将对象注入到web端
    21.         .javaScriptProxy({
    22.           object: this.testObj,
    23.           name: "testObjName",
    24.           methodList: ["test"],
    25.           controller: this.webviewController,
    26.           // 可选参数
    27.           asyncMethodList: [],
    28.           permission: '{"javascriptProxyPermission":{"urlPermissionList":[{"scheme":"resource","host":"rawfile","port":"","path":""},' +
    29.                       '{"scheme":"e","host":"f","port":"g","path":"h"}],"methodList":[{"methodName":"test","urlPermissionList":' +
    30.                       '[{"scheme":"https","host":"xxx.com","port":"","path":""},{"scheme":"resource","host":"rawfile","port":"","path":""}]},' +
    31.                       '{"methodName":"test11","urlPermissionList":[{"scheme":"q","host":"r","port":"","path":"t"},' +
    32.                       '{"scheme":"u","host":"v","port":"","path":""}]}]}}'
    33.         })
    34.     }
    35.   }
    36. }
    复制代码
  • 应用侧使用registerJavaScriptProxy()接口注册。
    1. // xxx.ets
    2. import { webview } from '@kit.ArkWeb';
    3. import { BusinessError } from '@kit.BasicServicesKit';
    4. class testClass {
    5.   constructor() {
    6.   }
    7.   test(): string {
    8.     return "ArkUI Web Component";
    9.   }
    10.   toString(): void {
    11.     console.log('Web Component toString');
    12.   }
    13. }
    14. @Entry
    15. @Component
    16. struct Index {
    17.   webviewController: webview.WebviewController = new webview.WebviewController();
    18.   @State testObj: testClass = new testClass();
    19.   build() {
    20.     Column() {
    21.       Button('refresh')
    22.         .onClick(() => {
    23.           try {
    24.             this.webviewController.refresh();
    25.           } catch (error) {
    26.             console.error(`ErrorCode: ${(error as BusinessError).code},  Message: ${(error as BusinessError).message}`);
    27.           }
    28.         })
    29.       Button('Register JavaScript To Window')
    30.         .onClick(() => {
    31.           try {
    32.             this.webviewController.registerJavaScriptProxy(this.testObj, "testObjName", ["test", "toString"],
    33.                     // 可选参数, asyncMethodList
    34.                     [],
    35.                     // 可选参数, permission
    36.                     '{"javascriptProxyPermission":{"urlPermissionList":[{"scheme":"resource","host":"rawfile","port":"","path":""},' +
    37.                     '{"scheme":"e","host":"f","port":"g","path":"h"}],"methodList":[{"methodName":"test","urlPermissionList":' +
    38.                     '[{"scheme":"https","host":"xxx.com","port":"","path":""},{"scheme":"resource","host":"rawfile","port":"","path":""}]},' +
    39.                     '{"methodName":"test11","urlPermissionList":[{"scheme":"q","host":"r","port":"","path":"t"},' +
    40.                     '{"scheme":"u","host":"v","port":"","path":""}]}]}}'
    41.             );
    42.           } catch (error) {
    43.             console.error(`ErrorCode: ${(error as BusinessError).code},  Message: ${(error as BusinessError).message}`);
    44.           }
    45.         })
    46.       Web({ src: $rawfile('index.html'), controller: this.webviewController })
    47.     }
    48.   }
    49. }
    复制代码
    阐明

    • 使用registerJavaScriptProxy()接口注册方法时,注册后需调用refresh()接口生效。
       
  • 可选参数permission是一个json字符串,示例如下:
    1. {
    2.   "javascriptProxyPermission": {
    3.     "urlPermissionList": [       // Object级权限,如果匹配,所有Method都授权
    4.       {
    5.         "scheme": "resource",    // 精确匹配,不能为空
    6.         "host": "rawfile",       // 精确匹配,不能为空
    7.         "port": "",              // 精确匹配,为空不检查
    8.         "path": ""               // 前缀匹配,为空不检查
    9.       },
    10.       {
    11.         "scheme": "https",       // 精确匹配,不能为空
    12.         "host": "xxx.com",       // 精确匹配,不能为空
    13.         "port": "8080",          // 精确匹配,为空不检查
    14.         "path": "a/b/c"          // 前缀匹配,为空不检查
    15.       }
    16.     ],
    17.     "methodList": [
    18.       {
    19.         "methodName": "test",
    20.         "urlPermissionList": [   // Method级权限
    21.           {
    22.             "scheme": "https",   // 精确匹配,不能为空
    23.             "host": "xxx.com",   // 精确匹配,不能为空
    24.             "port": "",          // 精确匹配,为空不检查
    25.             "path": ""           // 前缀匹配,为空不检查
    26.           },
    27.           {
    28.             "scheme": "resource",// 精确匹配,不能为空
    29.             "host": "rawfile",   // 精确匹配,不能为空
    30.             "port": "",          // 精确匹配,为空不检查
    31.             "path": ""           // 前缀匹配,为空不检查
    32.           }
    33.         ]
    34.       },
    35.       {
    36.         "methodName": "test11",
    37.         "urlPermissionList": [   // Method级权限
    38.           {
    39.             "scheme": "q",       // 精确匹配,不能为空
    40.             "host": "r",         // 精确匹配,不能为空
    41.             "port": "",          // 精确匹配,为空不检查
    42.             "path": "t"          // 前缀匹配,为空不检查
    43.           },
    44.           {
    45.             "scheme": "u",       // 精确匹配,不能为空
    46.             "host": "v",         // 精确匹配,不能为空
    47.             "port": "",          // 精确匹配,为空不检查
    48.             "path": ""           // 前缀匹配,为空不检查
    49.           }
    50.         ]
    51.       }
    52.     ]
    53.   }
    54. }
    复制代码
  • index.html前端页面触发应用侧代码。
    1. <!-- index.html -->
    2. <!DOCTYPE html>
    3. <html>
    4. <body>
    5. <button type="button" onclick="callArkTS()">Click Me!</button>
    6. <p id="demo"></p>
    7. <script>
    8.     function callArkTS() {
    9.         let str = testObjName.test();
    10.         document.getElementById("demo").innerHTML = str;
    11.         console.info('ArkTS Hello World! :' + str);
    12.     }
    13. </script>
    14. </body>
    15. </html>
    复制代码
复杂类型使用方法



  • 应用侧和前端页面之间转达Array。
    1. // xxx.ets
    2. import { webview } from '@kit.ArkWeb';
    3. import { BusinessError } from '@kit.BasicServicesKit';
    4. class testClass {
    5.   constructor() {
    6.   }
    7.   test(): Array<Number> {
    8.     return [1, 2, 3, 4]
    9.   }
    10.   toString(param: String): void {
    11.     console.log('Web Component toString' + param);
    12.   }
    13. }
    14. @Entry
    15. @Component
    16. struct Index {
    17.   webviewController: webview.WebviewController = new webview.WebviewController();
    18.   @State testObj: testClass = new testClass();
    19.   build() {
    20.     Column() {
    21.       Button('refresh')
    22.         .onClick(() => {
    23.           try {
    24.             this.webviewController.refresh();
    25.           } catch (error) {
    26.             console.error(`ErrorCode: ${(error as BusinessError).code},  Message: ${(error as BusinessError).message}`);
    27.           }
    28.         })
    29.       Button('Register JavaScript To Window')
    30.         .onClick(() => {
    31.           try {
    32.             this.webviewController.registerJavaScriptProxy(this.testObj, "testObjName", ["test", "toString"]);
    33.           } catch (error) {
    34.             console.error(`ErrorCode: ${(error as BusinessError).code},  Message: ${(error as BusinessError).message}`);
    35.           }
    36.         })
    37.       Web({ src: $rawfile('index.html'), controller: this.webviewController })
    38.     }
    39.   }
    40. }
    复制代码
    1. <!-- index.html -->
    2. <!DOCTYPE html>
    3. <html>
    4. <body>
    5. <button type="button" onclick="callArkTS()">Click Me!</button>
    6. <p id="demo"></p>
    7. <script>
    8.     function callArkTS() {
    9.         testObjName.toString(testObjName.test());
    10.     }
    11. </script>
    12. </body>
    13. </html>
    复制代码
  • 应用侧和前端页面之间转达基础类型,非Function等复杂类型。
    1. // xxx.ets
    2. import { webview } from '@kit.ArkWeb';
    3. import { BusinessError } from '@kit.BasicServicesKit';
    4. class student {
    5.   name: string = '';
    6.   age: string = '';
    7. }
    8. class testClass {
    9.   constructor() {
    10.   }
    11.   // 传递的基础类型name:"jeck", age:"12"。
    12.   test(): student {
    13.     let st: student = { name: "jeck", age: "12" };
    14.     return st;
    15.   }
    16.   toString(param: ESObject): void {
    17.     console.log('Web Component toString' + param["name"]);
    18.   }
    19. }
    20. @Entry
    21. @Component
    22. struct Index {
    23.   webviewController: webview.WebviewController = new webview.WebviewController();
    24.   @State testObj: testClass = new testClass();
    25.   build() {
    26.     Column() {
    27.       Button('refresh')
    28.         .onClick(() => {
    29.           try {
    30.             this.webviewController.refresh();
    31.           } catch (error) {
    32.             console.error(`ErrorCode: ${(error as BusinessError).code},  Message: ${(error as BusinessError).message}`);
    33.           }
    34.         })
    35.       Button('Register JavaScript To Window')
    36.         .onClick(() => {
    37.           try {
    38.             this.webviewController.registerJavaScriptProxy(this.testObj, "testObjName", ["test", "toString"]);
    39.           } catch (error) {
    40.             console.error(`ErrorCode: ${(error as BusinessError).code},  Message: ${(error as BusinessError).message}`);
    41.           }
    42.         })
    43.       Web({ src: $rawfile('index.html'), controller: this.webviewController })
    44.     }
    45.   }
    46. }
    复制代码
    1. <!-- index.html -->
    2. <!DOCTYPE html>
    3. <html>
    4. <body>
    5. <button type="button" onclick="callArkTS()">Click Me!</button>
    6. <p id="demo"></p>
    7. <script>
    8.     function callArkTS() {
    9.         testObjName.toString(testObjName.test());
    10.     }
    11. </script>
    12. </body>
    13. </html>
    复制代码
  • 应用侧调用前端页面的Callback。
    1. // xxx.ets
    2. import { webview } from '@kit.ArkWeb';
    3. import { BusinessError } from '@kit.BasicServicesKit';
    4. class testClass {
    5.   constructor() {
    6.   }
    7.   test(param: Function): void {
    8.     param("call callback");
    9.   }
    10.   toString(param: String): void {
    11.     console.log('Web Component toString' + param);
    12.   }
    13. }
    14. @Entry
    15. @Component
    16. struct Index {
    17.   webviewController: webview.WebviewController = new webview.WebviewController();
    18.   @State testObj: testClass = new testClass();
    19.   build() {
    20.     Column() {
    21.       Button('refresh')
    22.         .onClick(() => {
    23.           try {
    24.             this.webviewController.refresh();
    25.           } catch (error) {
    26.             console.error(`ErrorCode: ${(error as BusinessError).code},  Message: ${(error as BusinessError).message}`);
    27.           }
    28.         })
    29.       Button('Register JavaScript To Window')
    30.         .onClick(() => {
    31.           try {
    32.             this.webviewController.registerJavaScriptProxy(this.testObj, "testObjName", ["test", "toString"]);
    33.           } catch (error) {
    34.             console.error(`ErrorCode: ${(error as BusinessError).code},  Message: ${(error as BusinessError).message}`);
    35.           }
    36.         })
    37.       Web({ src: $rawfile('index.html'), controller: this.webviewController })
    38.     }
    39.   }
    40. }
    复制代码
    1. <!-- index.html -->
    2. <!DOCTYPE html>
    3. <html>
    4. <body>
    5. <button type="button" onclick="callArkTS()">Click Me!</button>
    6. <p id="demo"></p>
    7. <script>
    8.     function callArkTS() {
    9.         testObjName.test(function(param){testObjName.toString(param)});
    10.     }
    11. </script>
    12. </body>
    13. </html>
    复制代码
  • 应用侧调用前端页面Object里的Function。
    1. // xxx.ets
    2. import { webview } from '@kit.ArkWeb';
    3. import { BusinessError } from '@kit.BasicServicesKit';
    4. class testClass {
    5.   constructor() {
    6.   }
    7.   test(param: ESObject): void {
    8.     param.hello("call obj func");
    9.   }
    10.   toString(param: String): void {
    11.     console.log('Web Component toString' + param);
    12.   }
    13. }
    14. @Entry
    15. @Component
    16. struct Index {
    17.   webviewController: webview.WebviewController = new webview.WebviewController();
    18.   @State testObj: testClass = new testClass();
    19.   build() {
    20.     Column() {
    21.       Button('refresh')
    22.         .onClick(() => {
    23.           try {
    24.             this.webviewController.refresh();
    25.           } catch (error) {
    26.             console.error(`ErrorCode: ${(error as BusinessError).code},  Message: ${(error as BusinessError).message}`);
    27.           }
    28.         })
    29.       Button('Register JavaScript To Window')
    30.         .onClick(() => {
    31.           try {
    32.             this.webviewController.registerJavaScriptProxy(this.testObj, "testObjName", ["test", "toString"]);
    33.           } catch (error) {
    34.             console.error(`ErrorCode: ${(error as BusinessError).code},  Message: ${(error as BusinessError).message}`);
    35.           }
    36.         })
    37.       Web({ src: $rawfile('index.html'), controller: this.webviewController })
    38.     }
    39.   }
    40. }
    复制代码
    1. <!-- index.html -->
    2. <!DOCTYPE html>
    3. <html>
    4. <body>
    5. <button type="button" onclick="callArkTS()">Click Me!</button>
    6. <p id="demo"></p>
    7. <script>
    8.     // 写法1
    9.     class Student {
    10.         constructor(nameList) {
    11.             this.methodNameListForJsProxy = nameList;
    12.         }
    13.         hello(param) {
    14.             testObjName.toString(param)
    15.         }
    16.     }
    17.     var st = new Student(["hello"])
    18.     // 写法2
    19.     //创建一个构造器,构造函数首字母大写
    20.     function Obj1(){
    21.         this.methodNameListForJsProxy=["hello"];
    22.         this.hello=function(param){
    23.             testObjName.toString(param)
    24.         };
    25.     }
    26.     //利用构造器,通过new关键字生成对象
    27.     var st1 = new Obj1();
    28.     function callArkTS() {
    29.         testObjName.test(st);
    30.         testObjName.test(st1);
    31.     }
    32. </script>
    33. </body>
    34. </html>
    复制代码
  • 前端页面调用应用侧Object里的Function。
    1. // xxx.ets
    2. import { webview } from '@kit.ArkWeb';
    3. import { BusinessError } from '@kit.BasicServicesKit';
    4. class ObjOther {
    5.   methodNameListForJsProxy: string[]
    6.   constructor(list: string[]) {
    7.     this.methodNameListForJsProxy = list
    8.   }
    9.   testOther(json: string): void {
    10.     console.info(json)
    11.   }
    12. }
    13. class testClass {
    14.   ObjReturn: ObjOther
    15.   constructor() {
    16.     this.ObjReturn = new ObjOther(["testOther"]);
    17.   }
    18.   test(): ESObject {
    19.     return this.ObjReturn
    20.   }
    21.   toString(param: string): void {
    22.     console.log('Web Component toString' + param);
    23.   }
    24. }
    25. @Entry
    26. @Component
    27. struct Index {
    28.   webviewController: webview.WebviewController = new webview.WebviewController();
    29.   @State testObj: testClass = new testClass();
    30.   build() {
    31.     Column() {
    32.       Button('refresh')
    33.         .onClick(() => {
    34.           try {
    35.             this.webviewController.refresh();
    36.           } catch (error) {
    37.             console.error(`ErrorCode: ${(error as BusinessError).code},  Message: ${(error as BusinessError).message}`);
    38.           }
    39.         })
    40.       Button('Register JavaScript To Window')
    41.         .onClick(() => {
    42.           try {
    43.             this.webviewController.registerJavaScriptProxy(this.testObj, "testObjName", ["test", "toString"]);
    44.           } catch (error) {
    45.             console.error(`ErrorCode: ${(error as BusinessError).code},  Message: ${(error as BusinessError).message}`);
    46.           }
    47.         })
    48.       Web({ src: $rawfile('index.html'), controller: this.webviewController })
    49.     }
    50.   }
    51. }
    复制代码
    1. <!-- index.html -->
    2. <!DOCTYPE html>
    3. <html>
    4. <body>
    5. <button type="button" onclick="callArkTS()">Click Me!</button>
    6. <p id="demo"></p>
    7. <script>
    8.     function callArkTS() {
    9.       testObjName.test().testOther("call other object func");
    10.     }
    11. </script>
    12. </body>
    13. </html>
    复制代码
  • Promise场景。
    第一种使用方法,在应用侧new Promise。
    1. // xxx.ets
    2. import { webview } from '@kit.ArkWeb';
    3. import { BusinessError } from '@kit.BasicServicesKit';
    4. class testClass {
    5.   constructor() {
    6.   }
    7.   test(): Promise<string> {
    8.     let p: Promise<string> = new Promise((resolve, reject) => {
    9.       setTimeout(() => {
    10.         console.log('执行完成');
    11.         reject('fail');
    12.       }, 10000);
    13.     });
    14.     return p;
    15.   }
    16.   toString(param: String): void {
    17.     console.log(" " + param);
    18.   }
    19. }
    20. @Entry
    21. @Component
    22. struct Index {
    23.   webviewController: webview.WebviewController = new webview.WebviewController();
    24.   @State testObj: testClass = new testClass();
    25.   build() {
    26.     Column() {
    27.       Button('refresh')
    28.         .onClick(() => {
    29.           try {
    30.             this.webviewController.refresh();
    31.           } catch (error) {
    32.             console.error(`ErrorCode: ${(error as BusinessError).code},  Message: ${(error as BusinessError).message}`);
    33.           }
    34.         })
    35.       Button('Register JavaScript To Window')
    36.         .onClick(() => {
    37.           try {
    38.             this.webviewController.registerJavaScriptProxy(this.testObj, "testObjName", ["test", "toString"]);
    39.           } catch (error) {
    40.             console.error(`ErrorCode: ${(error as BusinessError).code},  Message: ${(error as BusinessError).message}`);
    41.           }
    42.         })
    43.       Web({ src: $rawfile('index.html'), controller: this.webviewController })
    44.     }
    45.   }
    46. }
    复制代码
    1. <!-- index.html -->
    2. <!DOCTYPE html>
    3. <html>
    4. <body>
    5. <button type="button" onclick="callArkTS()">Click Me!</button>
    6. <p id="demo"></p>
    7. <script>
    8.     function callArkTS() {
    9.       testObjName.test().then((param)=>{testObjName.toString(param)}).catch((param)=>{testObjName.toString(param)})
    10.     }
    11. </script>
    12. </body>
    13. </html>
    复制代码
    第二种使用方法,在前端页面new Promise。
    1. // xxx.ets
    2. import { webview } from '@kit.ArkWeb';
    3. import { BusinessError } from '@kit.BasicServicesKit';
    4. class testClass {
    5. constructor() {
    6. }
    7. test(param:Function): void {
    8. setTimeout( () => { param("suc") }, 10000)
    9. }
    10. toString(param:String): void {
    11. console.log(" " + param);
    12. }
    13. }
    14. @Entry
    15. @Component
    16. struct Index {
    17. webviewController: webview.WebviewController = new webview.WebviewController();
    18. @State testObj: testClass = new testClass();
    19. build() {
    20. Column() {
    21. Button('refresh')
    22. .onClick(() => {
    23. try {
    24. this.webviewController.refresh();
    25. } catch (error) {
    26. console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`);
    27. }
    28. })
    29. Button('Register JavaScript To Window')
    30. .onClick(() => {
    31. try {
    32. this.webviewController.registerJavaScriptProxy(this.testObj, "testObjName", ["test", "toString"]);
    33. } catch (error) {
    34. console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`);
    35. }
    36. })
    37. Web({ src: $rawfile('index.html'), controller: this.webviewController })
    38. }
    39. }
    40. }
    复制代码
    1. <!-- index.html -->
    2. <!DOCTYPE html>
    3. <html>
    4. <body>
    5. <button type="button" onclick="callArkTS()">Click Me!</button>
    6. <p id="demo"></p>
    7. <script>
    8.     function callArkTS() {
    9.       let funpromise
    10.       var p = new Promise(function(resolve, reject){funpromise=(param)=>{resolve(param)}})
    11.       testObjName.test(funpromise)
    12.       p.then((param)=>{testObjName.toString(param)})
    13.     }
    14. </script>
    15. </body>
    16. </html>
    复制代码


免责声明:如果侵犯了您的权益,请联系站长,我们会及时删除侵权内容,谢谢合作!更多信息从访问主页:qidao123.com:ToB企服之家,中国第一个企服评测及商务社交产业平台。

本帖子中包含更多资源

您需要 登录 才可以下载或查看,没有账号?立即注册

x
回复

使用道具 举报

0 个回复

倒序浏览

快速回复

您需要登录后才可以回帖 登录 or 立即注册

本版积分规则

瑞星

金牌会员
这个人很懒什么都没写!
快速回复 返回顶部 返回列表