-
-
Save rubo77/200f18c4bbf2f7bf88b56af8787c4c42 to your computer and use it in GitHub Desktop.
Adding alert() support to a WebView - Android
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* | |
Retrieved from https://web.archive.org/web/20160516165158/http://lexandera.com/2009/01/adding-alert-support-to-a-webview/ | |
*/ | |
// ... | |
import android.app.AlertDialog; | |
import android.content.Context; | |
import android.content.DialogInterface; | |
public class MainActivity extends AppCompatActivity { | |
private WebView webViewSpacetrace; | |
@Override | |
protected void onCreate(Bundle savedInstanceState) { | |
super.onCreate(savedInstanceState); | |
setContentView(R.layout.activity_main); | |
browser=(WebView) findViewById(R.id.yourBrowserViewId); | |
browser.setWebChromeClient(new WebChromeClient()); | |
browser.setWebViewClient(new WebViewClient()); | |
final WebView browser = (WebView)findViewById(R.id.browser); | |
/* JavaScript must be enabled if you want it to work, obviously */ | |
browser.getSettings().setJavaScriptEnabled(true); | |
final Context myApp = this; | |
/* WebChromeClient must be set BEFORE calling loadUrl! */ | |
browser.setWebChromeClient(new WebChromeClient() { | |
@Override | |
public boolean onJsAlert(WebView view, String url, String message, final android.webkit.JsResult result) | |
{ | |
new AlertDialog.Builder(myApp) | |
.setTitle("") | |
.setMessage(message) | |
.setPositiveButton(android.R.string.ok, | |
new AlertDialog.OnClickListener() | |
{ | |
public void onClick(DialogInterface dialog, int which) | |
{ | |
result.confirm(); | |
} | |
}) | |
.setCancelable(false) | |
.create() | |
.show(); | |
return true; | |
}; | |
}); | |
/* load a web page which uses the alert() function */ | |
browser.loadUrl("http://lexandera.com/files/jsexamples/alert.html"); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment