MKY's answer is effective if your focus is solely on triggering the alert
function. However, if you also need to address the functionalities of confirm
and prompt
, additional steps must be taken to override the onJsConfirm
and onJsPrompt
methods.
An important distinction between alert
and confirm
is that for confirm
, it is necessary to incorporate a setNegativeButton
that invokes the result.cancel()
method within the lambda expression.
Dealing with prompt
is more complex as it involves integrating a text editor into the dialog box. To achieve this, an EditText
object needs to be created and included in the dialog using AlertDialog.Builder.setView
, detailed in this specific response.
Furthermore, implementing a dismiss listener using setOnDismissListener
across all three dialogs is advisable to account for scenarios where the dialog may be dismissed through means other than button clicks. This could occur if the user presses the back button or selects an area outside the dialog.
The following comprehensive code accommodates alert
, confirm
, and prompt
situations. Remember to customize the placeholder "Title"
in each respective method according to your desired title preference.
webView.setWebChromeClient(new WebChromeClient(){
@Override
public boolean onJsAlert(WebView view, String url, String message, JsResult result){
new AlertDialog.Builder(view.getContext())
.setTitle("Title")
.setMessage(message)
.setPositiveButton("OK", (DialogInterface dialog, int which) -> result.confirm())
.setOnDismissListener((DialogInterface dialog) -> result.confirm())
.create()
.show();
return true;
}
@Override
public boolean onJsConfirm(WebView view, String url, String message, JsResult result){
new AlertDialog.Builder(view.getContext())
.setTitle("Title")
.setMessage(message)
.setPositiveButton("OK", (DialogInterface dialog, int which) -> result.confirm())
.setNegativeButton("Cancel", (DialogInterface dialog, int which) -> result.cancel())
.setOnDismissListener((DialogInterface dialog) -> result.cancel())
.create()
.show();
return true;
}
@Override
public boolean onJsPrompt(WebView view, String url, String message, String defaultValue, JsPromptResult result){
final EditText input = new EditText(view.getContext());
input.setInputType(InputType.TYPE_CLASS_TEXT);
input.setText(defaultValue);
new AlertDialog.Builder(view.getContext())
.setTitle("Title")
.setMessage(message)
.setView(input)
.setPositiveButton("OK", (DialogInterface dialog, int which) -> result.confirm(input.getText().toString()))
.setNegativeButton("Cancel", (DialogInterface dialog, int which) -> result.cancel())
.setOnDismissListener((DialogInterface dialog) -> result.cancel())
.create()
.show();
return true;
}
});