Yahor Urbanovich
Yahor Urbanovich

Reputation: 773

Input programmatically text in fields in webview after load page

I have some issue about WebView. I have some page. This page have two input fields.

We can input some text in field when the page is loading. But, can I set this fields after loading? For example, page opened and I choose some text in toolbar menu. After this text pasted in webView fields. It's really to realize? Thanks.

Upvotes: 1

Views: 3652

Answers (2)

user2433624
user2433624

Reputation: 59

The feedback from @DanielLaneDC helped me a lot just needed a little more info to get it working on my side. Hope it helps the next persone.

If your website has input fiels like so:

<input type="password" id="activeInput" autoaccept="true" value="">

I added a javascript function to my webserver:

function getFromAndroid(str){
    document.getElementById('activeInput').value = str;
}

In Android webview i called the javascript function:

webView.loadUrl("javascript:getFromAndroid('"+yourtext+"')");

if you didnt already make sure to add:

webSettings.setJavaScriptEnabled(true);

Upvotes: 0

DanielLaneDC
DanielLaneDC

Reputation: 1781

First let's break down the problem.

  • A webview will just load some HTML like a browser will. If you want to programmatically insert text into an input element in a webpage then we need to use javascript.

  • To Android, the webview is a view that handles its own drawing, we can interface with its methods and that's about it on a general level.

However, where these two meet is if we want to trigger some javascript to happen inside the webpage as a result of performing some action within the Android scope.

We still have to obey all of the rules that we described in our breaking down of the problem. Let's talk about it in those terms then: We need to interface with the webview's methods in such a way that it will use javascript to insert text into an input element.

So, now we know what we need:

  • JavaScript to insert text into an input element
  • A WebView method to use our JavaScript

The JavaScript is easy. Something like this will do the trick.

document.findElementById('my_text').value = 'My Text';

<input type='text' id='my_text' />

And thankfully there is such a WebView method we can use for this. It's fairly lengthy but quite straight forward and you can read all about it here.

Hope this helps.

Upvotes: 3

Related Questions