目录

Web场景下主动拉起软键盘

问题现象

Web组件加载H5页面,H5页面中有input输入框,如何实现刚进入H5页面就直接拉起软键盘?

背景知识

解决方案

H5页面有输入框时,可以在Web的onPageEnd回调中使用@ohos.inputMethod (输入法框架)框架的showTextInput方法实现页面加载时主动使输入框获焦并拉起键盘,inputMethod.TextConfig可以设置键盘的编辑框样式,attach方法将自绘控件与输入法绑定。

端侧示例代码如下:

import { webview } from '@kit.ArkWeb';
import { inputMethod } from '@kit.IMEKit';
import { BusinessError } from '@kit.BasicServicesKit';

let inputMethodController = inputMethod.getController();

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

  build() {
    Scroll() {
      Column() {
        Web({
          src: $rawfile('keyBoardDemo.html'),
          controller: this.controller,
        })
          .onPageEnd(() => {
            try {
              let textConfig: inputMethod.TextConfig = {
                inputAttribute: {
                  textInputType: 0,
                  enterKeyType: 1
                }
              };
              inputMethodController.attach(true, textConfig, (err: BusinessError) => {
                if (err) {
                  console.error(`Failed to attach: ${err.code} ${err.message}`);
                  return;
                }
                console.info('Succeeded in attaching the inputMethod.');
              });
            } catch (err) {
              console.error(`Failed to attach: ${err.code} ${err.message}`);
            }
            inputMethodController.showTextInput().then(() => {
              console.info('Succeeded in showing text input.');
            }).catch((err: BusinessError) => {
              console.error(`Failed to showTextInput: ${err.code} ${err.message}}`);
            });
          })
          .fileAccess(false)
          .geolocationAccess(false)
          .domStorageAccess(true)
          .height('100%');
      };
    };
  }
}

HTML示例代码如下:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport"
          content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
    <title>Document</title>
</head>
<body>
<h1>H5侧</h1>
<div>
    <input id="myInput" type="text" value="" style="margin:10px 0" onload/><br/>
</div>
</body>
<script>
    function test() {
       document.getElementById("myInput").focus();
    }
    // 加载时立即执行此函数
    document.addEventListener('DOMContentLoaded', test);
</script>
</html>
<style>
    body {
        width:100%;
        height:auto;
        margin:50px auto;
        text-align:center;
    }
</style>

常见FAQ

Q:滚动时如何收起键盘?

A:滚动时键盘不消失是系统的默认逻辑,可以通过Web组件的onScroll回调中使用stopInputSession收起键盘。