0

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?

Michael
  • 9,060
  • 14
  • 61
  • 123

1 Answers1

1

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;
 }
theduck
  • 2,589
  • 13
  • 17
  • 23
Asama
  • 385
  • 2
  • 14
  • I am interested in onJSPrompt (prompt), not onJSConfirm (alert) – Michael Nov 09 '16 at 19:45
  • I assume what I actually need is something similar, but instead of an AlertDialog I need something that actually fetches and returns text, but I'm not seeing a direct analog – Michael Nov 09 '16 at 19:47
  • Something like the answer to [this question](https://stackoverflow.com/questions/10903754/input-text-dialog-android) ... appears I still need an AlertDialog with a custom view – Michael Nov 09 '16 at 19:48
  • You may try replacing onJsConfirm with onPrompt code and leave alertdialog as is... These are similar. – Asama Nov 09 '16 at 19:50
  • Edited it to add a few lines that made the text entry part work. Thanks! – Michael Nov 09 '16 at 21:23
  • Edited to add "setOnCancelListener" otherwise the site will stay inresponsive bc result.cancel() was not called – Robert Apr 12 '21 at 12:38