Javascript – Android WebView always returns null for javascript getElementById on loadUrl


I try to fill out a form inside a webview from the android client app. I know how it should work, but the getElementById always returns null for me. I tried it on different websites.

Here is my example for

MyWebView view = new MyWebView(this);
view.setWebViewClient(new WebViewClient() {
    public boolean shouldOverrideUrlLoading(WebView v, String url) {
        return true;
    public void onPageFinished(WebView v, String url) {
        v.loadUrl("javascript:document.getElementById('mib').value = 'aaa';");              

And the MyWebView class (only for information).

class MyWebView extends WebView {
    Context context;
    public MyWebView(Context context) {
        this.context = context;
    public boolean onTouchEvent(MotionEvent event) {
        // do some multi touch stuff
        return true;

I always get the error:

09-01 04:35:26.453: I/chromium(2962): [INFO:CONSOLE(1)] "Uncaught TypeError: Cannot set property 'value' of null", source: (1)

But the element "mib" should be on the site. Using a desktop browser (chrome with mobile simulation) everything is working fine. I have no idea, whats going wrong here.

Thanks for hints!

I got some progress. Regarding this site, I also need setDomStorageEnabled(true).
No I can find the DOM object and set the value, but instead of showing the modified site I get a new blank one with only the value I set. E.g. a white blank site with the text "aaa".

Best Solution

Finally I found a solution! And it is a really strange behaviour.

First of all you need to specify setDomStorageEnabled(true) on your webview. Otherwise the DOM doesn't work. I wonder why no tutorial gave a hint about. But ok.


After this I ended up in a white blank page with only the value I set. The strange thing is, that javascript:document.getElementById('myfield').value = 'aaa'; returns a value. Namely the one I set. So a new blank page was created that only contains the string "aaa".

I solved it by modifying the javascript to throw away the return result:

javascript:var x = document.getElementById('myfield').value = 'aaa';

And voilá. It is working.