HarmonyOS application development Web component basic properties application and events

1. Overview of Web Components

Web components are used to display Web page content in applications and provide developers with page loading, page interaction, page debugging and other capabilities.

  • Page loading: Web components provide basic front-end page loading capabilities, including loading network pages, local pages, and Html format text data.
  • Page interaction: Web components provide a wealth of page interaction methods, including: setting the dark mode of the front-end page, loading the page in a new window, location permission management, cookie management, and the ability to use front-end page JavaScript on the application side.
  • Page debugging: Web components support using Devtools tools to debug front-end pages.

The following is a detailed introduction to the functional features of Web components through examples of common usage scenarios.

2. Load the page using web components

Page loading is the basic function of web components. According to the source of page loading data, it can be divided into three common scenarios, including loading network pages, loading local pages, and loading rich text data in HTML format.

During page loading, if network resource acquisition is involved, ohos.permission.INTERNET network access permission needs to be configured.

Load web page

Developers can specify the default loaded network page when creating a Web component. After the default page is loaded, if the developer needs to change the web page displayed by this web component, he can load the specified web page by calling the loadUrl() interface.

In the following example, after the web component loads the "www.example.com" page, the developer can change the page displayed by the web component to "www.example1.com" through the loadUrl interface.

// xxx.ets
import web_webview from '@ohos.web.webview';

@Entry
@Component
struct WebComponent {
       
       
  webviewController: web_webview.WebviewController = new web_webview.WebviewController();

  build() {
       
       
    Column() {
       
       
      Button('loadUrl')
        .onClick(() => {
       
       
          try {
       
       
            // 点击按钮时,通过loadUrl,跳转到www.example1.com
            this.webviewController.loadUrl('www.example1.com');
          } catch (error) {
       
       
            console.error(`ErrorCode: ${error.code},  Message: ${error.message}`);
          }
        })
      // 组件创建时,加载www.example.com
      Web({
       
        src: 'www.example.com', controller: this.webviewController})
    }
  }
}

Load local page

By placing the local page file in the rawfile directory of the application, developers can specify the local page to be loaded by default when creating the Web component, and after the loading is complete, the page of the current Web component can be changed by calling the loadUrl() interface .

The following example shows how to load a local page file:

  • Place the resource file in the application's resources/rawfile directory. Figure 1  Resource file path
  • Application side code
// xxx.ets
import web_webview from '@ohos.web.webview';

@Entry
@Component
struct WebComponent {
        
        
  webviewController: web_webview.WebviewController = new web_webview.WebviewController();

  build() {
        
        
    Column() {
        
        
      Button('loadUrl')
        .onClick(() => {
        
        
          try {
        
        
            // 点击按钮时,通过loadUrl,跳转到local1.html
            this.webviewController.loadUrl($rawfile("local1.html"));
          } catch (error) {
        
        
            console.error(`ErrorCode: ${error.code},  Message: ${error.message}`);
          }
        })
      // 组件创建时,通过$rawfile加载本地文件local.html
      Web({
        
         src: $rawfile("local.html"), controller: this.webviewController })
    }
  }
}

  • local.html page code .
<!-- local.html -->
<!DOCTYPE html>
<html>
  <body>
    <p>Hello World</p>
  </body>
</html>

Load text data in HTML format

Web components can load text data in HTML format through the loadData interface. When developers do not need to load the entire page, but only need to display some page fragments, this feature can be used to quickly load the page.

// xxx.ets
import web_webview from '@ohos.web.webview';

@Entry
@Component
struct WebComponent {
  controller: web_webview.WebviewController = new web_webview.WebviewController();

  build() {
    Column() {
      Button('loadData')
        .onClick(() => {
          try {
            // 点击按钮时,通过loadData,加载HTML格式的文本数据
            this.controller.loadData(
              '<html><body bgcolor="white">Source:<pre>source</pre></body></html>',
              'text/html',
              'UTF-8'
            );
          } catch (error) {
            console.error(`ErrorCode: ${error.code},  Message: ${error.message}`);
          }
        })
      // 组件创建时,加载www.example.com
      Web({ src: 'www.example.com', controller: this.controller })
    }
  }
}

3. Set basic properties and events

Set dark mode

Web components support dark mode configuration for front-end pages.

● Different dark modes can be configured through the darkMode() interface. WebDarkMode.Off mode means turning off the dark mode. WebDarkMode.On means turning on the dark mode, and the dark mode follows the front-end page. WebDarkMode.Auto means turning on the dark mode, and the dark mode follows the system. In the following example, the page dark mode is configured to follow the system through the darkMode() interface.

// xxx.ets
import web_webview from '@ohos.web.webview';

@Entry
@Component
struct WebComponent {
  controller: web_webview.WebviewController = new web_webview.WebviewController();
  @State mode: WebDarkMode = WebDarkMode.Auto;
  build() {
    Column() {
      Web({ src: 'www.example.com', controller: this.controller })
        .darkMode(this.mode)
    }
  }
}

The front-end page can be forced to configure dark mode through the forceDarkAccess() interface, and the dark mode does not follow the front-end page and the system. When configuring this mode, you need to configure the dark mode to WebDarkMode.On. In the following example, the page is forced to dark mode through the forceDarkAccess() interface.

// xxx.ets
import web_webview from '@ohos.web.webview';

@Entry
@Component
struct WebComponent {
  controller: web_webview.WebviewController = new web_webview.WebviewController();
  @State mode: WebDarkMode = WebDarkMode.On;
  @State access: boolean = true;
  build() {
    Column() {
      Web({ src: 'www.example.com', controller: this.controller })
        .darkMode(this.mode)
        .forceDarkAccess(this.access)
    }
  }
}

upload files

Web components support the front-end page selection file upload function. Application developers can use the onShowFileSelector() interface to handle front-end page file upload requests.

In the following example, when the user clicks the file upload button on the front-end page, the application side receives the file upload request in the onShowFileSelector() interface. In this interface, the developer sets the uploaded local file path to the front-end page.

● Application-side code.

// xxx.ets
import web_webview from '@ohos.web.webview';
@Entry
@Component
struct WebComponent {
  controller: WebController = new WebController()
  build() {
    Column() {
      // 加载本地local.html页面
      Web({ src: $rawfile('local.html'), controller: this.controller })
        .onShowFileSelector((event) => {
            // 开发者设置要上传的文件路径
           let fileList: Array<string> = [
              'xxx/test.png',
           ]
           event.result.handleFileList(fileList)
           return true;
        })
    }
  }
}

● local.html page code.

<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <title>Document</title>
</head>

<body>
// 点击文件上传按钮
<input type="file" value="file"></br>
</body>
</html>

Open page in new window

Web components provide the ability to open pages in new windows. Developers can use the multiWindowAccess() interface to set whether to allow web pages to be opened in new windows. When a new window opens, the application side will receive the Web component new window event in the onWindowNew() interface. Developers need to create a new window in this interface event to handle the Web component window request.

illustrate

● If the developer does not need to open a new window in the onWindowNew() interface notification, the return value of the ControllerHandler.setWebController() interface needs to be set to null.

As in the local example below, when the user clicks the "Open web page in new window" button, the application side will receive the Web component new window event in the onWindowNew() interface.

● Application-side code.

// xxx.ets
import web_webview from '@ohos.web.webview';
@Entry
@Component
struct WebComponent {
  controller: web_webview.WebviewController = new web_webview.WebviewController();
  build() {
    Column() {
      Web({ src:$rawfile("window.html"), controller: this.controller })
      .multiWindowAccess(true)
      .onWindowNew((event) => {
        console.info("onWindowNew...");
        var popController: web_webview.WebviewController = new web_webview.WebviewController();
        // 开发者需要在此处新建窗口,跟popController关联,并且将popController返回给Web组件。如果不需要打开新窗口请将返回值设置为event.handler.setWebController(null);
        event.handler.setWebController(popController);
      })
    }
  }
}

● window.html page code.

<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <title>WindowEvent</title>
</head>

<body>
<input type="button" value="新窗口中打开网页" onclick="OpenNewWindow()">
<script type="text/javascript">
    function OpenNewWindow()
    {
        let openedWindow = window.open("about:blank", "", "location=no,status=no,scrollvars=no");
        if (openedWindow) {
            openedWindow.document.body.write("<p>这是我的窗口</p>");
        } else {
            log.innerHTML = "window.open failed";
        }
    }
</script>
</body>
</html>

Manage location permissions

Web components provide location permission management capabilities. Developers can manage location permissions for a website through the onGeolocationShow() interface. The web component decides whether to grant permissions to the front-end page based on the interface response result. To obtain the device location, developers need to configure the ohos.permission.LOCATION permission.

In the following example, the user clicks the "Get Location" button on the front-end page, and the web component notifies the application side of the location permission request message through a pop-up window. The sample code is as follows:

● Front-end page code.

<!DOCTYPE html>
<html>
<body>
<p id="locationInfo">位置信息</p>
<button onclick="getLocation()">获取位置</button>
<script>
var locationInfo=document.getElementById("locationInfo");
function getLocation(){
  if (navigator.geolocation) {
    <!-- 前端页面访问设备地理位置 -->
    navigator.geolocation.getCurrentPosition(showPosition);
  }
}
function showPosition(position){
  locationInfo.innerHTML="Latitude: " + position.coords.latitude + "<br />Longitude: " + position.coords.longitude;
}
</script>
</body>
</html>

● Application code.

// xxx.ets
import web_webview from '@ohos.web.webview';

@Entry
@Component
struct WebComponent {
  controller: web_webview.WebviewController = new web_webview.WebviewController();
  build() {
    Column() {
      Web({ src:$rawfile('getLocation.html'), controller:this.controller })
        .geolocationAccess(true)
        .onGeolocationShow((event) => {  // 地理位置权限申请通知
          AlertDialog.show({
            title: '位置权限请求',
            message: '是否允许获取位置信息',
            primaryButton: {
              value: 'cancel',
              action: () => {
                event.geolocation.invoke(event.origin, false, false);   // 不允许此站点地理位置权限请求
              }
            },
            secondaryButton: {
              value: 'ok',
              action: () => {
                event.geolocation.invoke(event.origin, true, false);    // 允许此站点地理位置权限请求
              }
            },
            cancel: () => {
              event.geolocation.invoke(event.origin, false, false);   // 不允许此站点地理位置权限请求
            }
          })
        })
    }
  }
}

Guess you like

Origin blog.csdn.net/HarmonyOSDev/article/details/132897586