介紹
本示例介紹了@ohos.web.webview組件和Web以及CustomDialog接口實現H5頁面調用自定義輸入法的功能。該場景多用于瀏覽器需要使用安全輸入法時。
效果圖預覽
使用說明:
- 點擊密碼輸入框,彈出自定義鍵盤。
- 在自定義鍵盤上輸入內容,能成功映射到h5頁面內。
實現步驟
實現H5頁面調用自定義輸入法,有兩個關鍵點,一是需要將arkTS方法注冊到h5頁面中;二是要實現彈出鍵盤的組件。
- 構建一個 Browser 對象,集成瀏覽器的方法。創建一個自定義組件 TabletTitle,構成瀏覽器的工具欄。
// 自定義瀏覽器對象
export class Browser {
inputValue: string = "";
progress: number = 0;
isRegistered: boolean = false;
hideProgress: boolean = true;
tabsController: TabsController = new TabsController();
webController: WebviewController = new web_webview.WebviewController();
// 跳轉頁面
loadUrl(addr: string | Resource) {
this.webController.loadUrl(addr);
}
// 返回頁面
back(): boolean {
if (this.webController.accessBackward()) {
this.webController.backward();
return true;
}
return false;
}
// 前進頁面
forward() {
if (this.webController.accessForward()) {
this.webController.forward();
}
}
// 刷新頁面
refresh() {
this.webController.refresh();
}
}
- 自定義鍵盤傳入js對象 WebKeyboardObj, 構建兩個函數:點擊登錄按鈕事件和輸入法彈窗彈出事件。其中輸入法彈出事件中使用CustomDialog修飾的組件,打開自定義彈窗。
dialogController: CustomDialogController | null = new CustomDialogController({
builder: CustomKeyboard({
dialogClose: this.dialogClose,
items: this.items,
inputValue: this.inputValue,
curKeyboardType: this.curKeyboardType,
onKeyboardEvent: this.onKeyboardEvent,
closeDialog: this.closeDialog
}),
isModal: false,
alignment: DialogAlignment.Bottom,
customStyle: true
});
// ...
webKeyboardObj: WebKeyboardObj = {
// 點擊登錄按鈕事件
login: () => {
promptAction.showToast({
message: $r('app.string.custom_keyboard_to_h5_login_button'),
duration: 2000
});
this.closeDialog();
},
// 輸入法彈窗彈出事件
openDialog: (value: string) => {
this.dialogController?.open();
this.dialogClose = false;
if (value?.length) {
this.inputValue = value;
}
}
}
- 將webKeyboardObj對象通過webController.registerJavaScriptProxy 注冊到h5頁面中,使頁面中可以調用arkTS的方法。
// 注冊方法到h5的js中
registerFunc(browser: Browser) {
if (!browser.isRegistered) {
browser.webController.registerJavaScriptProxy(this.webKeyboardObj, 'etsObj',
['login', 'openDialog'])
browser.isRegistered = true;
browser.webController.refresh();
}
}
- 構建一個h5頁面,在js層中調用注冊進入的arkTS方法。
<script>
function tapInput() {
document.activeElement.blur();
let input = document.getElementById("searchCon");
etsObj.openDialog(input.value); // 打開自定義彈窗
}
function setInput(value) {
let input = document.getElementById("searchCon");
input.value = value;
}
function login() {
etsObj.login(); // 點擊登錄按鈕
}
</script>
寫在最后
- 如果你覺得這篇內容對你還蠻有幫助,我想邀請你幫我三個小忙:
- 點贊,轉發,有你們的 『點贊和評論』,才是我創造的動力。
- 關注小編,同時可以期待后續文章ing??,不定期分享原創知識。
- 想要獲取更多完整鴻蒙最新學習知識點,請移步前往小編:
https://gitee.com/MNxiaona/733GH/blob/master/jianshu