默認狀況下,在WebView中是不能使用javascript的。能夠經過書寫下面的代碼:javascript
WebView myWebView = (WebView) findViewById(R.id.webview);
WebSettings webSettings = myWebView.getSettings();
webSettings.setJavaScriptEnabled(true);java
而後就能夠使用了。web
綁定javascript和Android代碼:ide
例如:你能夠在你的應用程序中建立一個類:this
public class JavaScriptInterface {
Context mContext;
/** Instantiate the interface and set the context */
JavaScriptInterface(Context c) {
mContext = c;
}
/** Show a toast from the web page */
public void showToast(String toast) {
Toast.makeText(mContext, toast, Toast.LENGTH_SHORT).show();
}
}url
綁定javascript,定義的接口名稱爲Android。spa
WebView webView = (WebView) findViewById(R.id.webview);
webView.addJavascriptInterface(new JavaScriptInterface(this), "Android");線程
而後在你的HTML代碼中寫:orm
<input type="button" value="Say hello" onClick="showAndroidToast('Hello Android!')" />
<script type="text/javascript">
function showAndroidToast(toast) {
Android.showToast(toast);
}
</script>接口
注意:綁定的javascript運行在另外一個線程中,與建立它的線程不是同一個。
處理頁面導航:
默認狀況下,當你單擊你的WebView頁面的連接時,鏈接到URIs。你能夠使用下面的方式鏈接到你本身的WebView。
WebView myWebView = (WebView) findViewById(R.id.webview);
myWebView.serWebViewClient(new WebViewClient());
如何你想控制更多的點擊鏈接的話,能夠重寫shouldOverrideUrlLoading()方法,建立本身的WebViewClient:
private class MyWebViewClient extends WebViewClient {
@Override
public boolean shouldOverrideLoading(WebView view, String url) {
if (Uri.parse(url).getHost().equals("www.example.com")) {
// This is my web site, so do not override; let my WebView load the page
return false;
}
// Otherwise, the link is not for a page on my site, so launch another Activity that handles URLs
Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(url));
startActivity(intent);
return true;
}
}
經過下面的方式來訪問歷史頁:
public boolean onKeyDown(int keyCode, KeyEvent event) {
// Check if the key event was the BACK key and if there's history
if ((keyCode == KeyEvent.KEYCODE_BACK) && myWebView.canGoBack() {
myWebView.goBack();
return true;
}
// If it wasn't the BACK key or there's no web page history, bubble up to the default
// system behavior (probably exit the activity)
return super.onKeyDown(keyCode, event);
}