[Hongmeng Application ArkTS Development Series] - Explanation on the use of web components

Table of contents

1. Introduction to Web Components

2. Create components

Permission list

3. Set styles and attributes

4. Add events and methods

5. Access local Html

1. Create local html files

2. Load local html files

2. JS object injection, Html uses JS objects to call client methods

3. The client calls the JS method in the local Html web page


When using Hongmeng's ArkUI framework to develop Hongmeng applications, the official provides us with a web component for developers to use. Through this article, we will understand and learn how to use web components to perform the following operations:

  • Online web page loading
  • Local offline web page loading
  • Common property settings for web components
  • Two-way communication interaction between client and web page

Let's first take a look at the introduction of Web components.

1. Introduction to Web Components

Web is a component that provides web page display capabilities. For specific usage, please refer to  Web API .

2. Create components

Create a Page page of WebComponent .ets in the pages directory, and place a Web component on the page. In the Web component, specify the referenced web page path through src. The controller is the controller of the component. The Web component is bound through the controller to call the method of the Web component.

​

@Entry

@Component

struct WebComponent {

  controller: WebController = new WebController();

  build() {

    Column() {

      Web({ src: 'https://www.douban.com/', controller: this.controller })

    }

  }

}

​

To use Web components to access online web pages, you need to configure network permissions for the application.

Permission list

When accessing online web pages, you need to add network permission: ohos.permission.INTERNET

3. Set styles and attributes

The use of web components requires adding rich page styles and functional attributes. Setting the height and padding styles can add height and padding to the Web component. Setting the fileAccess attribute can add file access permissions to the Web component. Setting the javaScriptAccess attribute to true enables the Web component to have the ability to execute JavaScript code.

​

@Entry

@Component

struct WebComponent {

  fileAccess: boolean = true;

  controller: WebController = new WebController();

  build() {

    Column() {

      Text('Hello world!')

        .fontSize(20)

      Web({ src: 'https://www.douban.com/', controller: this.controller })

        // 设置高和内边距

        .height(500)

        .padding(20)

        // 设置文件访问权限和脚本执行权限

        .fileAccess(this.fileAccess)

        .javaScriptAccess(true)

      Text('End')

        .fontSize(20)

    }

  }

}

​

4. Add events and methods

Add the onProgressChange event for the Web component, which calls back the progress value of the web engine loading the page. Assign the progress value to the value of the Progress component to control the status of the Progress component. When the progress is 100%, the Progress component is hidden and the web page is loaded.

​
import web_view from '@ohos.web.webview';

@Entry

@Component

struct RemoteWebPage {

  @State progress: number = 0

  @State hideProgress: boolean = true

  controller: web_view.WebviewController = new web_view.WebviewController()

  build() {

    Column() {

      Progress({ total: 100, value: this.progress })

        .color('#ff5cea20')

        .visibility(this.hideProgress ? Visibility.None : Visibility.Visible)

      Web({ src: 'https://www.douban.com/', controller: this.controller })

        .height('100%')

        // 添加onProgressChange事件

        .onProgressChange(e => {

          this.progress = e.newProgress

         // 当进度100%时,进度条消失

          if (this.progress == 100) {

            this.hideProgress = true

          } else {

            this.hideProgress = false

          }

        })

    }.backgroundColor('0xFFFFFF')

  }

}

​

The effect is as follows:

The above is about using Web components to access an online web page. How to load local web page files?

5. Access local Html

Let’s look at the renderings first

Implemented a method of loading local web page files, and then calling the client in the Html web page, and implemented a function to close the page and pull up the system album. Let's start with the code implementation.

1. Create local html files

In the entry/src/main/resources/rawfile directory, we create an index.html file

<!-- index.html -->

<!DOCTYPE html>

<html>

<body>

<p>Hello World</p>

<p>这个是来自本地的html文件</p>



<button type="button" onclick="window.jsBridge.closePage()">点击调用原生关闭页面</button>

<button type="button" onclick="window.jsBridge.jumpSystemPicture()">点击拉起原生系统相册</button>

</body>

</html>

2. Load local html files

Create a LocalWebPage page and load the index.html file

import web_view from '@ohos.web.webview';



@Entry

@Component

struct LocalWebPage {

  controller: web_view.WebviewController = new web_view.WebviewController()



  build() {

    Column() {

      Web({ src: $rawfile("index.html"), controller: this.controller })

        .height('100%')

    }

  }

}

Here we use $rawfile("index.html") to obtain local html files.

2. JS object injection, Html uses JS objects to call client methods

If we need to interact with the client on the web page, we need to set up a JS object to be injected into Html, as follows:

import web_view from '@ohos.web.webview';

import common from '@ohos.app.ability.common';

import router from '@ohos.router';



@Entry

@Component

struct LocalWebPage {

  controller: web_view.WebviewController = new web_view.WebviewController()



  jsBridge = {



    jumpSystemPicture() {



      let context = getContext(this) as common.UIAbilityContext;



      let want  = {

          "deviceId": "",

          "bundleName": "",

          "abilityName": "",

          "uri": "",

          "type": "image/*",

          "action": "android.intent.action.GET_CONTENT",

          "parameters":{},

          "entities":[]



      };

      context.startAbility(want);

    },



    closePage() {

      router.back()

    }

  }



  build() {

    Column() {

      Web({ src: $rawfile("index.html"), controller: this.controller })

        .javaScriptAccess(true)

        .javaScriptProxy({

          object: this.jsBridge,

          name: "jsBridge",

          methodList: ["closePage","jumpSystemPicture"],

          controller: this.controller

        })

        .height('100%')

    }

  }

}

Here we define a JS object jsBridge and define two methods, jumpSystemPicture and closePage, which are used to pull up the system album and close the client page in html respectively, and then use the javaScriptProxy method of the Web to perform JS object injection settings. The specific configuration is as above Code, you need to configure the object name and injection method.

Take a look at the Html code calling JS above, such as calling the client's page close method, using

window.jsBridge.closePage() is triggered.

3. The client calls the JS method in the local Html web page

Add runJavaScript method in onPageEnd event. The onPageEnd event is a callback when the web page is loaded, and the runJavaScript method can execute JavaScript scripts in HTML. When the page is loaded, the onPageEnd event is triggered, the test method in the HTML file is called, and the information is printed on the console.

import web_view from '@ohos.web.webview';

import router from '@ohos.router';



@Entry

@Component

struct LocalWebPage {

  controller: web_view.WebviewController = new web_view.WebviewController()





  build() {

    Column() {

      Web({ src: $rawfile("index.html"), controller: this.controller })

        .javaScriptAccess(true)

      .onPageEnd(e =>{

          // test()在index.html中定义

          this.controller.runJavaScript('test()');

          console.info('url: ', e.url);

        })

        .height('100%')

    }

  }

}
<!-- index.html -->

<!DOCTYPE html>

<html>

<body>

<p>Hello World</p>

<p>这个是来自本地的html文件</p>



<button type="button" onclick="window.jsBridge.closePage()">点击调用原生关闭页面</button>

<button type="button" onclick="window.jsBridge.jumpSystemPicture()">点击拉起原生系统相册</button>

</body>

<script type="text/javascript">

  function test() {

      console.info('Ark Web Component');

  }

</script>

</html>

The above method only mentions calling the JS method in the web page. If you want to asynchronously obtain the data returned by the JS method, how should you do it? If you are interested, pay attention to the discussion in the comment area. I will add more explanations when I have time.

This article ends here, thank you for reading!

Guess you like

Origin blog.csdn.net/q919233914/article/details/130081872