• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1# 前端页面调用应用侧函数
2
3
4开发者使用Web组件将应用侧代码注册到前端页面中,注册完成之后,前端页面中使用注册的对象名称就可以调用应用侧的函数,实现在前端页面中调用应用侧方法。
5
6
7注册应用侧代码有两种方式,一种在Web组件初始化调用,使用[javaScriptProxy()](../reference/apis-arkweb/ts-basic-components-web.md#javascriptproxy)接口。另外一种在Web组件初始化完成后调用,使用[registerJavaScriptProxy()](../reference/apis-arkweb/js-apis-webview.md#registerjavascriptproxy)接口。
8
9
10在下面的示例中,将test()方法注册在前端页面中, 该函数可以在前端页面触发运行。
11
12
13- [javaScriptProxy()](../reference/apis-arkweb/ts-basic-components-web.md#javascriptproxy)接口使用示例如下。
14
15  ```ts
16  // xxx.ets
17  import web_webview from '@ohos.web.webview';
18
19  class testClass {
20    constructor() {
21    }
22
23    test(): string {
24      return 'ArkTS Hello World!';
25    }
26  }
27
28  @Entry
29  @Component
30  struct WebComponent {
31    webviewController: web_webview.WebviewController = new web_webview.WebviewController();
32    // 声明需要注册的对象
33    @State testObj: testClass = new testClass();
34
35    build() {
36      Column() {
37        // web组件加载本地index.html页面
38        Web({ src: $rawfile('index.html'), controller: this.webviewController})
39          // 将对象注入到web端
40          .javaScriptProxy({
41            object: this.testObj,
42            name: "testObjName",
43            methodList: ["test"],
44            controller: this.webviewController
45          })
46      }
47    }
48  }
49  ```
50
51
52- 应用侧使用registerJavaScriptProxy()接口注册。
53
54  ```ts
55  // xxx.ets
56  import web_webview from '@ohos.web.webview';
57  import business_error from '@ohos.base';
58
59  class testClass {
60    constructor() {
61    }
62
63    test(): string {
64      return "ArkUI Web Component";
65    }
66
67    toString(): void {
68      console.log('Web Component toString');
69    }
70  }
71
72  @Entry
73  @Component
74  struct Index {
75    webviewController: web_webview.WebviewController = new web_webview.WebviewController();
76    @State testObj: testClass = new testClass();
77
78    build() {
79      Column() {
80        Button('refresh')
81          .onClick(() => {
82            try {
83              this.webviewController.refresh();
84            } catch (error) {
85              let e: business_error.BusinessError = error as business_error.BusinessError;
86              console.error(`ErrorCode: ${e.code},  Message: ${e.message}`);
87            }
88          })
89        Button('Register JavaScript To Window')
90          .onClick(() => {
91            try {
92              this.webviewController.registerJavaScriptProxy(this.testObj, "testObjName", ["test", "toString"]);
93            } catch (error) {
94              let e: business_error.BusinessError = error as business_error.BusinessError;
95              console.error(`ErrorCode: ${e.code},  Message: ${e.message}`);
96            }
97          })
98        Web({ src: $rawfile('index.html'), controller: this.webviewController })
99      }
100    }
101  }
102  ```
103
104  > **说明:**
105  >
106  > 使用[registerJavaScriptProxy()](../reference/apis-arkweb/js-apis-webview.md#registerjavascriptproxy)接口注册方法时,注册后需调用[refresh()](../reference/apis-arkweb/js-apis-webview.md#refresh)接口生效。
107
108
109- index.html前端页面触发应用侧代码。
110
111  ```html
112  <!-- index.html -->
113  <!DOCTYPE html>
114  <html>
115  <body>
116  <button type="button" onclick="callArkTS()">Click Me!</button>
117  <p id="demo"></p>
118  <script>
119      function callArkTS() {
120          let str = testObjName.test();
121          document.getElementById("demo").innerHTML = str;
122          console.info('ArkTS Hello World! :' + str);
123      }
124  </script>
125  </body>
126  </html>
127  ```
128## 复杂类型使用方法
129- 应用侧和前端页面之间传递Array。
130  ```ts
131  // xxx.ets
132  import web_webview from '@ohos.web.webview';
133  import business_error from '@ohos.base';
134
135  class testClass {
136    constructor() {
137    }
138
139    test(): Array<Number>{
140      return [1, 2, 3, 4]
141    }
142
143    toString(param:String): void {
144      console.log('Web Component toString' + param);
145    }
146  }
147
148  @Entry
149  @Component
150  struct Index {
151    webviewController: web_webview.WebviewController = new web_webview.WebviewController();
152    @State testObj: testClass = new testClass();
153
154    build() {
155      Column() {
156        Button('refresh')
157          .onClick(() => {
158            try {
159              this.webviewController.refresh();
160            } catch (error) {
161              let e: business_error.BusinessError = error as business_error.BusinessError;
162              console.error(`ErrorCode: ${e.code},  Message: ${e.message}`);
163            }
164          })
165        Button('Register JavaScript To Window')
166          .onClick(() => {
167            try {
168              this.webviewController.registerJavaScriptProxy(this.testObj, "testObjName", ["test", "toString"]);
169            } catch (error) {
170              let e: business_error.BusinessError = error as business_error.BusinessError;
171              console.error(`ErrorCode: ${e.code},  Message: ${e.message}`);
172            }
173          })
174        Web({ src: $rawfile('index.html'), controller: this.webviewController })
175      }
176    }
177  }
178  ```
179
180  ```html
181  <!-- index.html -->
182  <!DOCTYPE html>
183  <html>
184  <body>
185  <button type="button" onclick="callArkTS()">Click Me!</button>
186  <p id="demo"></p>
187  <script>
188      function callArkTS() {
189          testObjName.toString(testObjName.test());
190      }
191  </script>
192  </body>
193  </html>
194  ```
195- 应用侧和前端页面之间传递不带Function的Dictionary。
196  ```ts
197  // xxx.ets
198  import web_webview from '@ohos.web.webview';
199  import business_error from '@ohos.base';
200
201  class student {
202    name: string = ''
203    age: string = ''
204  }
205
206  class testClass {
207    constructor() {
208    }
209
210    test(): student {
211      let st: student = {name:"jeck", age:"12"}
212      return st
213    }
214
215    toString(param: ESObject): void {
216      console.log('Web Component toString' + param["name"]);
217    }
218  }
219
220  @Entry
221  @Component
222  struct Index {
223    webviewController: web_webview.WebviewController = new web_webview.WebviewController();
224    @State testObj: testClass = new testClass();
225
226    build() {
227      Column() {
228        Button('refresh')
229          .onClick(() => {
230            try {
231              this.webviewController.refresh();
232            } catch (error) {
233              let e: business_error.BusinessError = error as business_error.BusinessError;
234              console.error(`ErrorCode: ${e.code},  Message: ${e.message}`);
235            }
236          })
237        Button('Register JavaScript To Window')
238          .onClick(() => {
239            try {
240              this.webviewController.registerJavaScriptProxy(this.testObj, "testObjName", ["test", "toString"]);
241            } catch (error) {
242              let e: business_error.BusinessError = error as business_error.BusinessError;
243              console.error(`ErrorCode: ${e.code},  Message: ${e.message}`);
244            }
245          })
246        Web({ src: $rawfile('index.html'), controller: this.webviewController })
247      }
248    }
249  }
250  ```
251
252  ```html
253  <!-- index.html -->
254  <!DOCTYPE html>
255  <html>
256  <body>
257  <button type="button" onclick="callArkTS()">Click Me!</button>
258  <p id="demo"></p>
259  <script>
260      function callArkTS() {
261          testObjName.toString(testObjName.test());
262      }
263  </script>
264  </body>
265  </html>
266  ```
267
268- 应用侧调用前端页面的Callback。
269  ```ts
270  // xxx.ets
271  import web_webview from '@ohos.web.webview';
272  import business_error from '@ohos.base';
273
274  class testClass {
275    constructor() {
276    }
277
278    test(param: Function): void {
279      param("call callback");
280    }
281
282    toString(param:String): void {
283      console.log('Web Component toString' + param);
284    }
285  }
286
287  @Entry
288  @Component
289  struct Index {
290    webviewController: web_webview.WebviewController = new web_webview.WebviewController();
291    @State testObj: testClass = new testClass();
292
293    build() {
294      Column() {
295        Button('refresh')
296          .onClick(() => {
297            try {
298              this.webviewController.refresh();
299            } catch (error) {
300              let e: business_error.BusinessError = error as business_error.BusinessError;
301              console.error(`ErrorCode: ${e.code},  Message: ${e.message}`);
302            }
303          })
304        Button('Register JavaScript To Window')
305          .onClick(() => {
306            try {
307              this.webviewController.registerJavaScriptProxy(this.testObj, "testObjName", ["test", "toString"]);
308            } catch (error) {
309              let e: business_error.BusinessError = error as business_error.BusinessError;
310              console.error(`ErrorCode: ${e.code},  Message: ${e.message}`);
311            }
312          })
313        Web({ src: $rawfile('index.html'), controller: this.webviewController })
314      }
315    }
316  }
317  ```
318
319  ```html
320  <!-- index.html -->
321  <!DOCTYPE html>
322  <html>
323  <body>
324  <button type="button" onclick="callArkTS()">Click Me!</button>
325  <p id="demo"></p>
326  <script>
327      function callArkTS() {
328          testObjName.test(function(param){testObjName.toString(param)});
329      }
330  </script>
331  </body>
332  </html>
333  ```
334
335- 应用侧调用前端页面Object里的Function。
336  ```ts
337  // xxx.ets
338  import web_webview from '@ohos.web.webview';
339  import business_error from '@ohos.base';
340
341  class testClass {
342    constructor() {
343    }
344
345    test(param: ESObject): void {
346      param.hello("call obj func");
347    }
348
349    toString(param:String): void {
350      console.log('Web Component toString' + param);
351    }
352  }
353
354  @Entry
355  @Component
356  struct Index {
357    webviewController: web_webview.WebviewController = new web_webview.WebviewController();
358    @State testObj: testClass = new testClass();
359
360    build() {
361      Column() {
362        Button('refresh')
363          .onClick(() => {
364            try {
365              this.webviewController.refresh();
366            } catch (error) {
367              let e: business_error.BusinessError = error as business_error.BusinessError;
368              console.error(`ErrorCode: ${e.code},  Message: ${e.message}`);
369            }
370          })
371        Button('Register JavaScript To Window')
372          .onClick(() => {
373            try {
374              this.webviewController.registerJavaScriptProxy(this.testObj, "testObjName", ["test", "toString"]);
375            } catch (error) {
376              let e: business_error.BusinessError = error as business_error.BusinessError;
377              console.error(`ErrorCode: ${e.code},  Message: ${e.message}`);
378            }
379          })
380        Web({ src: $rawfile('index.html'), controller: this.webviewController })
381      }
382    }
383  }
384  ```
385
386  ```html
387  <!-- index.html -->
388  <!DOCTYPE html>
389  <html>
390  <body>
391  <button type="button" onclick="callArkTS()">Click Me!</button>
392  <p id="demo"></p>
393  <script>
394      // 写法1
395      class Student {
396          constructor(nameList) {
397              this.methodNameListForJsProxy = nameList;
398          }
399
400          hello(param) {
401              testObjName.toString(param)
402          }
403      }
404      var st = new Student(["hello"])
405
406      // 写法2
407      //创建一个构造器,构造函数首字母大写
408      function Obj1(){
409          this.methodNameListForJsProxy=["hello"];
410          this.hello=function(param){
411              testObjName.toString(param)
412          };
413      }
414      //利用构造器,通过new关键字生成对象
415      var st1 = new Obj1();
416
417      function callArkTS() {
418          testObjName.test(st);
419          testObjName.test(st1);
420      }
421  </script>
422  </body>
423  </html>
424  ```
425
426- 前端页面调用应用侧Object里的Function。
427  ```ts
428  // xxx.ets
429  import web_webview from '@ohos.web.webview';
430  import business_error from '@ohos.base';
431
432  class ObjOther {
433      methodNameListForJsProxy: string[]
434
435      constructor(list: string[]) {
436          this.methodNameListForJsProxy = list
437      }
438
439      testOther(json:string): void {
440          console.info(json)
441      }
442  }
443
444  class testClass {
445    ObjReturn:ObjOther
446    constructor() {
447      this.ObjReturn =  new ObjOther(["testOther"]);
448    }
449
450    test(): ESObject {
451      return this.ObjReturn
452    }
453
454    toString(param: string): void {
455      console.log('Web Component toString' + param);
456    }
457  }
458
459  @Entry
460  @Component
461  struct Index {
462    webviewController: web_webview.WebviewController = new web_webview.WebviewController();
463    @State testObj: testClass = new testClass();
464
465    build() {
466      Column() {
467        Button('refresh')
468          .onClick(() => {
469            try {
470              this.webviewController.refresh();
471            } catch (error) {
472              let e: business_error.BusinessError = error as business_error.BusinessError;
473              console.error(`ErrorCode: ${e.code},  Message: ${e.message}`);
474            }
475          })
476        Button('Register JavaScript To Window')
477          .onClick(() => {
478            try {
479              this.webviewController.registerJavaScriptProxy(this.testObj, "testObjName", ["test", "toString"]);
480            } catch (error) {
481              let e: business_error.BusinessError = error as business_error.BusinessError;
482              console.error(`ErrorCode: ${e.code},  Message: ${e.message}`);
483            }
484          })
485        Web({ src: $rawfile('index.html'), controller: this.webviewController })
486      }
487    }
488  }
489  ```
490
491  ```html
492  <!-- index.html -->
493  <!DOCTYPE html>
494  <html>
495  <body>
496  <button type="button" onclick="callArkTS()">Click Me!</button>
497  <p id="demo"></p>
498  <script>
499      function callArkTS() {
500        testObjName.test().testOther("call other object func");
501      }
502  </script>
503  </body>
504  </html>
505  ```
506
507- Promise场景。<br>
508  第一种使用方法,在应用侧new Promise。
509  ```ts
510  // xxx.ets
511  import web_webview from '@ohos.web.webview';
512  import business_error from '@ohos.base';
513
514  class testClass {
515    constructor() {
516    }
517
518    test(): Promise<string> {
519        let p: Promise<string> = new Promise((resolve, reject) => {  setTimeout(() => {console.log('执行完成'); reject('fail');}, 10000);});
520        return p;
521    }
522
523    toString(param:String): void {
524        console.log(" " + param)
525    }
526  }
527
528  @Entry
529  @Component
530  struct Index {
531    webviewController: web_webview.WebviewController = new web_webview.WebviewController();
532    @State testObj: testClass = new testClass();
533
534    build() {
535      Column() {
536        Button('refresh')
537          .onClick(() => {
538            try {
539              this.webviewController.refresh();
540            } catch (error) {
541              let e: business_error.BusinessError = error as business_error.BusinessError;
542              console.error(`ErrorCode: ${e.code},  Message: ${e.message}`);
543            }
544          })
545        Button('Register JavaScript To Window')
546          .onClick(() => {
547            try {
548              this.webviewController.registerJavaScriptProxy(this.testObj, "testObjName", ["test", "toString"]);
549            } catch (error) {
550              let e: business_error.BusinessError = error as business_error.BusinessError;
551              console.error(`ErrorCode: ${e.code},  Message: ${e.message}`);
552            }
553          })
554        Web({ src: $rawfile('index.html'), controller: this.webviewController })
555      }
556    }
557  }
558  ```
559
560  ```html
561  <!-- index.html -->
562  <!DOCTYPE html>
563  <html>
564  <body>
565  <button type="button" onclick="callArkTS()">Click Me!</button>
566  <p id="demo"></p>
567  <script>
568      function callArkTS() {
569        testObjName.test().then((param)=>{testObjName.toString(param)}).catch((param)=>{testObjName.toString(param)})
570      }
571  </script>
572  </body>
573  </html>
574  ```
575  第二种使用方法,在前端页面new Promise。
576  ```ts
577  // xxx.ets
578  import web_webview from '@ohos.web.webview';
579  import business_error from '@ohos.base';
580
581  class testClass {
582    constructor() {
583    }
584
585    test(param:Function): void {
586        setTimeout( () => { param("suc") }, 10000)
587    }
588
589    toString(param:String): void {
590        console.log(" " + param)
591    }
592  }
593
594  @Entry
595  @Component
596  struct Index {
597    webviewController: web_webview.WebviewController = new web_webview.WebviewController();
598    @State testObj: testClass = new testClass();
599
600    build() {
601      Column() {
602        Button('refresh')
603          .onClick(() => {
604            try {
605              this.webviewController.refresh();
606            } catch (error) {
607              let e: business_error.BusinessError = error as business_error.BusinessError;
608              console.error(`ErrorCode: ${e.code},  Message: ${e.message}`);
609            }
610          })
611        Button('Register JavaScript To Window')
612          .onClick(() => {
613            try {
614              this.webviewController.registerJavaScriptProxy(this.testObj, "testObjName", ["test", "toString"]);
615            } catch (error) {
616              let e: business_error.BusinessError = error as business_error.BusinessError;
617              console.error(`ErrorCode: ${e.code},  Message: ${e.message}`);
618            }
619          })
620        Web({ src: $rawfile('index.html'), controller: this.webviewController })
621      }
622    }
623  }
624  ```
625
626  ```html
627  <!-- index.html -->
628  <!DOCTYPE html>
629  <html>
630  <body>
631  <button type="button" onclick="callArkTS()">Click Me!</button>
632  <p id="demo"></p>
633  <script>
634      function callArkTS() {
635        let funpromise
636        var p = new Promise(function(resolve, reject){funpromise=(param)=>{resolve(param)}})
637        testObjName.test(funpromise)
638        p.then((param)=>{testObjName.toString(param)})
639      }
640  </script>
641  </body>
642  </html>
643  ```
644