I want my WebView to display a prompt just like a web browser would.
From other answers addressing alert(), I found that I must do something like this in my Java code:
myWebView = (WebView) findViewById(R.id.webview);
WebSettings webSettings = myWebView.getSettings();
webSettings.setJavaScriptEnabled(true);
myWebView.addJavascriptInterface(new WebAppInterface(this), "Android");
// Next line was added
myWebView.setWebChromeClient(new WebChromeClient());
This works, and the prompt pops up, but instead of displaying the message I pass to prompt()
, it instead says:
The page at "https:..." says:
In javascript my call looks like this:
prompt("Test")
So I would expect the prompt to say "Test".
This totally breaks the immersion of the WebView being embedded in an app. How do I get the WebChromeClient to display the text I actually pass?
You need to create an AlertDialog
in onJsPrompt
under WebChromeClient
and attach an EditText as its view like so:
@Override boolean onJsPrompt (WebView view, String url, String message, String defaultValue, JsPromptResult result) {
final EditText input = new EditText(main);
input.setInputType(InputType.TYPE_CLASS_TEXT);
input.setText(defaultValue);
new AlertDialog.Builder(myApp)
.setTitle("App Titler")
.setView(input)
.setMessage(message)
.setPositiveButton(android.R.string.ok, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
result.confirm(input.getText().toString());
}
})
.setNegativeButton(android.R.string.cancel, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
result.cancel();
}
})
.create()
.show();
return true;
}