W3Cschool
恭喜您成為首批注冊(cè)用戶
獲得88經(jīng)驗(yàn)值獎(jiǎng)勵(lì)
開(kāi)發(fā)者使用Web組件將應(yīng)用側(cè)代碼注冊(cè)到前端頁(yè)面中,注冊(cè)完成之后,前端頁(yè)面中使用注冊(cè)的對(duì)象名稱就可以調(diào)用應(yīng)用側(cè)的函數(shù),實(shí)現(xiàn)在前端頁(yè)面中調(diào)用應(yīng)用側(cè)方法。
注冊(cè)應(yīng)用側(cè)代碼有兩種方式,一種在Web組件初始化使用調(diào)用,使用javaScriptProxy()接口。另外一種在Web組件初始化完成后調(diào)用,使用registerJavaScriptProxy()接口。
在下面的示例中,將test()方法注冊(cè)在前端頁(yè)面中, 該函數(shù)可以在前端頁(yè)面觸發(fā)運(yùn)行。
- // xxx.ets
- import web_webview from '@ohos.web.webview';
- class testClass {
- constructor() {
- }
- test(): string {
- return 'ArkTS Hello World!';
- }
- }
- @Entry
- @Component
- struct WebComponent {
- webviewController: web_webview.WebviewController = new web_webview.WebviewController();
- // 聲明需要注冊(cè)的對(duì)象
- @State testObj: testClass = new testClass();
- build() {
- Column() {
- // web組件加載本地index.html頁(yè)面
- Web({ src: $rawfile('index.html'), controller: this.webviewController})
- // 將對(duì)象注入到web端
- .javaScriptProxy({
- object: this.testObj,
- name: "testObjName",
- methodList: ["test"],
- controller: this.webviewController
- })
- }
- }
- }
- // xxx.ets
- import web_webview from '@ohos.web.webview';
- import business_error from '@ohos.base';
- class testClass {
- constructor() {
- }
- test(): string {
- return "ArkUI Web Component";
- }
- toString(): void {
- console.log('Web Component toString');
- }
- }
- @Entry
- @Component
- struct Index {
- webviewController: web_webview.WebviewController = new web_webview.WebviewController();
- @State testObj: testClass = new testClass();
- build() {
- Column() {
- Button('refresh')
- .onClick(() => {
- try {
- this.webviewController.refresh();
- } catch (error) {
- let e: business_error.BusinessError = error as business_error.BusinessError;
- console.error(`ErrorCode: ${e.code}, Message: ${e.message}`);
- }
- })
- Button('Register JavaScript To Window')
- .onClick(() => {
- try {
- this.webviewController.registerJavaScriptProxy(this.testObj, "testObjName", ["test", "toString"]);
- } catch (error) {
- let e: business_error.BusinessError = error as business_error.BusinessError;
- console.error(`ErrorCode: ${e.code}, Message: ${e.message}`);
- }
- })
- Web({ src: $rawfile('index.html'), controller: this.webviewController })
- }
- }
- }
使用registerJavaScriptProxy()接口注冊(cè)方法時(shí),注冊(cè)后需調(diào)用refresh()接口生效。
- <!-- index.html -->
- <!DOCTYPE html>
- <html>
- <body>
- <button type="button" onclick="callArkTS()">Click Me!</button>
- <p id="demo"></p>
- <script>
- function callArkTS() {
- let str = testObjName.test();
- document.getElementById("demo").innerHTML = str;
- console.info('ArkTS Hello World! :' + str);
- }
- </script>
- </body>
- </html>
Copyright©2021 w3cschool編程獅|閩ICP備15016281號(hào)-3|閩公網(wǎng)安備35020302033924號(hào)
違法和不良信息舉報(bào)電話:173-0602-2364|舉報(bào)郵箱:jubao@eeedong.com
掃描二維碼
下載編程獅App
編程獅公眾號(hào)
聯(lián)系方式:
更多建議: