1

I am using webview_flutter.

I currently have a native login page in my app that takes in a user's name and password. I am trying to find a way to automatically fill in the username and password on the specific page in webview and submit the login request.

Tried doing this

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

but got the following errors:

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})

Greatly appreciate any help on this. Thank you.

karmelcorn
  • 512
  • 1
  • 5
  • 12
  • I recommend you use a questring approach than javascript (as code below shows) as you go against several security issues. Something like: "webviewController.loadUrl('https://yourdomain.extension?u=user@gmail.com&p=xyz')" all encrypted obviosly. – G3nt_M3caj Aug 29 '20 at 21:34

1 Answers1

3

The code works, I put it in the wrong place.

The code should be placed under onPageFinished. I had it under onWebViewCreated previously.

The following code works correctly.

            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);
                  },
                ),

karmelcorn
  • 512
  • 1
  • 5
  • 12