Flutter_Webview 鍵盤彈出問題

Flutter_Webview 鍵盤彈出問題javascript


webview_flutter ^0.3.7+1 pub連接java

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

1.來自其餘同窗的啓發

隱藏TextField方案,這個方案的簡單思路就是在onPageFinish時給Webview注入一段js代碼,監聽input/textarea的focus事件,而後經過JSChannel發送給隱藏在WebView以後的TextField,經過TextField間接喚起軟鍵盤而後,經過監聽TextField的onChange事件給input/textarea設置新的值github

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

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:json

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來喚起/隱藏 軟鍵盤ide

這個方案看起來很好,可是手寫監聽全部Classname可太笨了...並且若是用戶在彈出鍵盤後手動關閉鍵盤(按軟鍵盤上的關閉按鈕),軟鍵盤就再也彈不出來了...post

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被點擊時:ui

*  先判斷是否是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標籤做爲按鈕的可能還要手動隱藏下鍵盤,以上.

相關文章
相關標籤/搜索