JavaScript not working in Android Webview?

David K picture David K · Sep 25, 2011 · Viewed 80.7k times · Source

I'm trying to make an Android version of a relativly simple iOS app that uses a webview, some buttons and then relies on javascript calls to a CMS.

But I'm stuck at a pretty early point of development: The webview doesn't function with javascript.I've read a lot of posts about how to enable JS in an Android webview, but no luck so far.

Below is some of my code:

public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);

    mWebView = (WebView) findViewById(R.id.webview);
    mWebView.getSettings().setJavaScriptEnabled(true);
    mWebView.setWebChromeClient(new WebChromeClient());
    mWebView.setWebViewClient(new HelloWebViewClient()
    {
        @Override  
        public void onPageFinished(WebView view, String url)  
        {  
            //Calling an init method that tells the website, we're ready 
            mWebView.loadUrl("javascript:m2Init()");
            page1(mWebView);
        }  
    });
  mWebView.loadUrl("http://my_url/mobile/iphone//app.php");  
}

private class HelloWebViewClient extends WebViewClient {
    @Override
    public boolean shouldOverrideUrlLoading(WebView view, String url) {
        view.loadUrl(url);
        return true;
    }

}


@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
    if ((keyCode == KeyEvent.KEYCODE_BACK) && mWebView.canGoBack()) {
        mWebView.goBack();
        return true;
    }
    return super.onKeyDown(keyCode, event);
}

public void page11(View view)
{
    mWebView.loadUrl("javascript:m2LoadPage(1)");
}

What am I doing wrong here? The URL is working perfectly in my iOS app, and in a browser. But not in my app!

Please tell me it's something obvious...

Answer

David K picture David K · Sep 26, 2011

FIXED! Spurred on by the error, I found out that I needed to set

setDomStorageEnabled(true)

for the webview settings.

Thanks for your help Stephan :)