Flutter_Webview 鍵盤彈出問題

apm29發表於2019-06-07

Flutter_Webview 鍵盤彈出問題


webview_flutter ^0.3.7+1 pub連結

webview_flutter在Android上沒有辦法彈出鍵盤,github上的issue已經提了很久,但是官方的milestone還要到19年的十月 issue #19718,(截止發稿時已經有一個PR到master分支了,但是stable分支的同學可能就還要等一哈了),但是PR的解決方案在AndroidN之前並沒有用...comment

1.來自其他同學的啟發

隱藏TextField方案,這個方案的簡單思路就是在onPageFinish時給Webview注入一段js程式碼,監聽input/textarea的focus事件,然後通過JSChannel傳送給隱藏在WebView之後的TextField,通過TextField間接喚起軟鍵盤然後,通過監聽TextField的onChange事件給input/textarea設定新的值

下面是他的JS程式碼實現:他用js監聽某個網站的幾個需要彈出輸入法的element,focus事件/focusout事件

inputs = document.getElementsByClassName('search-bar');
                            header=document.getElementsByClassName('site-header');
                            header[0].style.display = 'none';
buttons = document.getElementsByClassName('icon');
                            buttons[0].focus();
                            if (inputs != null) {
                              input = inputs[0];
                              InputValue.postMessage(input.value);
                              input.addEventListener('focus', (_) => {
                                Focus.postMessage('focus');
                              }, true);
                              input.addEventListener('focusout', (_) => {
                                Focus.postMessage('focusout');
                              }, true)
                            }
複製程式碼

JSChannel:

 javascriptChannels: Set.from(
                          [
                            // Listening for Javascript messages to get Notified of Focuschanges and the current input Value of the Textfield.
                            JavascriptChannel(
                              name: 'Focus',
                              // get notified of focus changes on the input field and open/close the Keyboard.
                              onMessageReceived: (JavascriptMessage focus) {
                                print(focus.message);
                                if (focus.message == 'focus') {
                                  FocusScope.of(context)
                                      .requestFocus(_focusNode);
                                } else if (focus.message == 'focusout') {
                                  _focusNode.unfocus();
                                }
                              },
                            ),
                            JavascriptChannel(
                              name: 'InputValue',
                              // set the value of the native input field to the one on the website to always make sure they have the same input.
                              onMessageReceived: (JavascriptMessage value) {
                                _textController.value =
                                    TextEditingValue(text: value.toString());
                              },
                            )
                          ],
                        ),
複製程式碼

接收事件更改TextField的text,通過focusNode來喚起/隱藏 軟鍵盤

這個方案看起來很好,但是手寫監聽所有Classname可太笨了...而且如果使用者在彈出鍵盤後手動關閉鍵盤(按軟鍵盤上的關閉按鈕),軟鍵盤就再也彈不出來了...

2.自己的方案升級

  1. 用兩個TextField交替接收事件來解決無法在手動關閉鍵盤後重新喚起的問題
  2. 注入JS監聽所有input/textarea element,不監聽focus/focusout事件,監聽click事件,有幾個好處 1. 可以獲取使用者當前文字選擇/游標位置 2. 可以判斷再次點選事件
  3. 記錄當前focus的element,用於判斷是否需要重新喚起新的鍵盤

下面的簡單的程式碼實現:

var inputs = document.getElementsByTagName('input');
var textArea = document.getElementsByTagName('textarea');
var current;

for (var i = 0; i < inputs.length; i++) {
  console.log(i);
  inputs[i].addEventListener('click', (e) => {
    var json = {
      "funcName": "requestFocus",
      "data": {
        "initText": e.target.value,
        "selectionStart":e.target.selectionStart,
        "selectionEnd":e.target.selectionEnd
      }
    };
    json.data.refocus = (document.activeElement == current);
    
    current = e.target;
    var param = JSON.stringify(json);
    console.log(param);
    UserState.postMessage(param);
  })
  
}
for (var i = 0; i < textArea.length; i++) {
  console.log(i);
  textArea[i].addEventListener('click', (e) => {
    var json = {
      "funcName": "requestFocus",
      "data": {
        "initText": e.target.value,
        "selectionStart":e.target.selectionStart,
        "selectionEnd":e.target.selectionEnd
      }
    };
    
    json.data.refocus = (document.activeElement == current);
    
    current = e.target;
    var param = JSON.stringify(json);
    console.log(param);
    
    UserState.postMessage(param);
  })
};
console.log('===JS CODE INJECTED INTO MY WEBVIEW===');
複製程式碼

UserState是定義好的jsChannel,接收一個jsonString形式的引數,data.initText是初始文字,selectEnd selectStart是文字選擇位置,refocus是判斷是否重新點選focus的Element的標記,element被點選時:

*  先判斷是不是refocus,傳送給channel
複製程式碼

接下來要處理JSChannel收到的資料了,其中showAndroidKeyboard是自己編寫的一個PlatformChannel,用來顯示軟鍵盤,程式碼還可以簡化,我這裡就不寫了,有改進的請和作者聯絡…也是在踩坑中.

  • 關鍵是TextField交替獲取焦點,當TextField - A獲取焦點,進行一番編輯之後,使用者手動關閉了軟鍵盤,這個時候FocusScop.of(context).requestFocus(focusNodeA)是無法喚起鍵盤的,所以需要另一個TextField-B來請求焦點,
  • showAndroidKeyboard()是為了在某些情況下備用focusNode也沒獲取焦點,需要我們手動喚起焦點
  • 隱藏鍵盤的事件還沒有很好的解決方案
bool refocus = data['refocus'] as bool;
    if (_focusNode2.hasFocus) {
      if (!refocus) FocusScope.of(context).requestFocus(_focusNode1);
      //FocusScope.of(context).requestFocus(_focusNode);
      if (!_focusNode1.hasFocus) {
        //hideAndroidKeyboard();
        showAndroidKeyboard();
      }
      //把初始文字設定給隱藏TextField
      String initText = data['initText'];
      var selectionStart = data['selectionStart'];
      var selectionEnd = data['selectionEnd'];

      int end = initText.length;
      int start = initText.length;
      if (selectionEnd is int) {
        end = selectionEnd;
      }
      if (selectionStart is int) {
        start = selectionEnd;
      }
      print(selectionEnd);
      textController1.value = TextEditingValue(
        text: initText,
        selection: TextSelection(baseOffset: start, extentOffset: end),
      );
      //TextField請求顯示鍵盤
      FocusScope.of(context).requestFocus(_focusNode1);
    } else {
      if (!refocus) FocusScope.of(context).requestFocus(_focusNode2);
      //FocusScope.of(context).requestFocus(_focusNode);
      if (!_focusNode2.hasFocus) {
        //hideAndroidKeyboard();
        showAndroidKeyboard();
      }
      //把初始文字設定給隱藏TextField
      String initText = data['initText'];
      var selectionStart = data['selectionStart'];
      var selectionEnd = data['selectionEnd'];

      int end = initText.length;
      int start = initText.length;
      if (selectionEnd is int) {
        end = selectionEnd;
      }
      if (selectionStart is int) {
        start = selectionEnd;
      }
      print(selectionEnd);
      textController2.value = TextEditingValue(
        text: initText,
        selection: TextSelection(baseOffset: start, extentOffset: end),
      );
      //TextField請求顯示鍵盤
      FocusScope.of(context).requestFocus(_focusNode2);
    }
複製程式碼

webview後面隱藏的TextField

return Stack(
                  children: <Widget>[
                    TextField(
                      autofocus: false,
                      focusNode: _focusNode1,
                      controller: textController1,
                      onChanged: (text) {
                        controller.evaluateJavascript('''
                         if(current != null){
                          current.value = '${textController1.text}';
                          current.selectionStart = ${textController1.selection.start};
                          current.selectionEnd = ${textController1.selection.end};
                          current.dispatchEvent(new Event('input'));
                         }
                        ''');
                      },
                      onSubmitted: (text) {
                        controller.evaluateJavascript('''
                        if(current != null)
                          current.submit();
                        ''');
                        _focusNode1.unfocus();
                      },
                    ),
                    TextField(
                      autofocus: false,
                      focusNode: _focusNode2,
                      controller: textController2,
                      onChanged: (text) {
                        controller.evaluateJavascript('''
                         if(current != null){
                          current.value = '${textController2.text}';
                          current.selectionStart = ${textController2.selection.start};
                          current.selectionEnd = ${textController2.selection.end};
                          current.dispatchEvent(new Event('input'));
                         }
                        ''');
                      },
                      onSubmitted: (text) {
                        controller.evaluateJavascript('''
                        if(current != null)
                          current.submit();
                        ''');
                        _focusNode2.unfocus();
                      },
                    ),
                    WebView(....)
                  ]
  );
複製程式碼
  • 在TextField的onChange中改編當前focus的Element的text/selection,然後傳送一個input事件來觸發Element改變current.dispatchEvent(new Event('input'));,這裡的大家應該都很好理解了.

不得不說谷歌太坑了,webview竟然有這樣的大缺陷,不過也沒辦法畢竟版本號還沒到1.0.0呢…本文的方法只是一個臨時的解決方案,比如點選空白隱藏軟鍵盤等功能還沒實現,只使用一些簡單的文字輸入的webview還是可以的,還有一些input標籤作為按鈕的可能還要手動隱藏下鍵盤,以上.

相關文章