By default, javascript cannot be used in WebView. You can write the following code:
WebView myWebView = (WebView) findViewById (R. id. webview );
WebSettings webSettings = myWebView. getSettings ();
WebSettings. setJavaScriptEnabled (true );
Then you can use it.
Bind javascript and Android code:
For example, you can create a class in your application:
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 ();
}
}
Binds javascript. The interface name is Android.
WebView webView = (WebView) findViewById (R. id. webview );
WebView. addJavascriptInterface (new JavaScriptInterface (this), "Android ");
Then write in your HTML code:
<Input type = "button" value = "Say hello" onClick = "showAndroidToast ('Hello Android! ') "/>
<Script type = "text/javascript">
Function showAndroidToast (toast ){
Android. showToast (toast );
}
</Script>
Note: The bound javascript runs in another thread, which is not the same as the thread that created it.
Processing page navigation:
By default, When you click the link to your WebView page, connect to the URL. You can use the following method to connect to your own WebView.
WebView myWebView = (WebView) findViewById (R. id. webview );
MyWebView. serWebViewClient (new WebViewClient ());
To control more click connections, you can override the shouldOverrideUrlLoading () method to create your own 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;
}
}
You can access the history page in the following ways:
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 );
}
From: column of Yan Longan