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