Search code examples
androidandroid-webviewandroid-toast

Is there a way to convert Javascript alerts to show as Toast in Android WebView?


I have a web app thats working with Javascript alerts on most pages. Now I have recently created a WebView application for the same app. The app works fine, the alerts show.

I've seen solutions that suggest binding JavaScript code to Android code and then call these methods for example to show toast.

I have no doubt that this works, but now, for me, this means I'd have to re-write the code(s) that trigger these alerts.

My question is, is there a way to automatically capture all the alerts and display their contents as toasts instead?


Solution

  • Thanks to Moonbloom's answer and this answer also.I managed to come with a solution that works exactly as I wanted. So for anyone who will stumble upon the same issue in the future, the snippet below is for you:

    
            mWebView.setWebChromeClient(new WebChromeClient() {
                @Override
                public boolean onJsAlert(WebView view, String url, String message,
                                         final JsResult result) {
                    Toast.makeText(getApplicationContext(), message, Toast.LENGTH_LONG).show();
                    result.confirm();
                    return true;
                }
            });
    

    Where mWebView is a WebView instance.