Android WebView JavaScript alert

Android WebView

By default, Android doesn’t handle JavaScript alert();
The reason is that Android handles UI by itself. (To change UI, we need to use main thread of Android).
To handle this problem, we need to implement client.
It means that it happens this situation, we ask WebView to handle this.

Example

UI

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    app:layout_behavior="@string/appbar_scrolling_view_behavior"
    tools:context="jp.co.rakuten.toolbar.webviewtest.MainActivity"
    tools:showIn="@layout/activity_main">
 
    <WebView
        android:id="@+id/webview"
        android:layout_width="match_parent"
        android:layout_height="match_parent">
    </WebView>
 
</RelativeLayout>

HTML

<html>
<head>
    <title>JavaScript</title>
    <script>
        function test() {
            alert("OK");
        }
    </script>
</head>
<body>
<button onclick="test();">Click me!</button>
</body>
</html>

Java

public class MainActivity extends AppCompatActivity {

    private WebView webView;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);

        webView = (WebView) findViewById(R.id.webview);

        webView.getSettings().setJavaScriptEnabled(true);

        // Load local webview
        webView.loadUrl("file:///android_asset/index.html");


        webView.setWebChromeClient(new WebChromeClient() {

            @Override
            public boolean onJsAlert(WebView view, String url, String message, JsResult result) {
                return super.onJsAlert(view, url, message, result);
            }
        });

    }
}

To add setWebChromeClient and implement onJSAlert
Of course, we can change UI as Alert dialog. If you use super.onJsAlert, open Android dialog by default.