0

我正在使用 webview_flutter。

我目前在我的应用程序中有一个本机登录页面,其中包含用户名和密码。我正在尝试找到一种方法来在webview的特定页面上自动填写用户名和密码并提交登录请求。

试过这样做

webViewController.evaluateJavascript(
                          '''
     var email = document.getElementById("CustomerEmail");
     var password = document.getElementById("CustomerPassword");
     email.value = "user@gmail.com";
     password.value = "test123";
   '''
                      );

但出现以下错误:

Error Domain=WKErrorDomain Code=4 "A JavaScript exception occurred" UserInfo={WKJavaScriptExceptionLineNumber=3, WKJavaScriptExceptionMessage=TypeError: null is not an object (evaluating 'email.value = "user@gmail.com"'), WKJavaScriptExceptionColumnNumber=11, WKJavaScriptExceptionSourceURL=undefined, NSLocalizedDescription=A JavaScript exception occurred})

非常感谢您对此的任何帮助。谢谢你。

4

1 回答 1

2

代码有效,我把它放在错误的地方。

代码应放在 onPageFinished 下。我之前在 onWebViewCreated 下有它。

以下代码可以正常工作。

            WebView(
                  initialUrl: widget.url,
                  onPageFinished: (_) {
                    setState(() {
                    print("loggedin " + loggedIn.toString());

                    if(loggedIn == false) {
                      loggedIn = true;
                        _controller.future
                            .then((value) =>
                            value.evaluateJavascript('''
                             var email = document.getElementById("CustomerEmail");
                             var password = document.getElementById("CustomerPassword");
                             email.value = "user@gmail.com";
                             password.value = "test123";
                             document.getElementById('customer_login').submit();
                           '''));
                        
                      }

                      
                    });
                  },
                  javascriptMode: JavascriptMode.unrestricted,
                  onWebViewCreated: (WebViewController webViewController) {
                    _controller.complete(webViewController);
                  },
                ),

于 2020-08-29T23:03:53.193 回答