Android中在WebView中使用javascript

默认状况下,在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);
}

相关文章
相关标签/搜索