Android WebView与JavaScript交互

1.安卓执行JS代码

webView.loadUrl("javascript:(function(){这里是需要执行JS代码})()");

注意最后的()为js闭包,一定要书写

2.JS调用安卓代码

js调用安卓代码采用addJavascriptInterface方法,用下如下

切记:在API7后要用@JavascriptInterface注解本地的js方法,不然会提示找不到方法

package com.apkfuns.androidjsdemo; import android.app.AlertDialog; import android.os.Bundle; import android.util.Log; import android.view.Menu; import android.view.MenuItem; import android.webkit.JavascriptInterface; import android.webkit.JsResult; import android.webkit.WebChromeClient; import android.webkit.WebView; import android.webkit.WebViewClient; public class MainActivity extends BaseActivity { private WebView webView; public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activitymain); webView = getViewById(R.id.webView); webView.getSettings().setJavaScriptEnabled(true); webView.addJavascriptInterface(new OnJavaScriptLocalObject(), "localObject"); webView.loadUrl("https://www.baidu.com"); webView.getSettings().setJavaScriptCanOpenWindowsAutomatically(true); webView.getSettings().setDomStorageEnabled(true); webView.setWebViewClient(new WebViewClient(){ public boolean shouldOverrideUrlLoading(WebView view, String url) { view.loadUrl(url); return true; } }); } @Override public boolean onCreateOptionsMenu(Menu menu) { getMenuInflater().inflate(R.menu.menumain, menu); return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { if(item.getItemId() == R.id.add_btn){ webView.loadUrl("javascript:(function(){" + "var btn = document.createElement(\"button\");" + "btn.innerHTML = \"JS调用Android代码\"; "+ "btn.style.backgroundColor = \"#EAECED\";"+ "btn.style.border=\"1px solid #BDC1C1\";"+ "btn.style.padding=\"8px\";"+ "btn.onclick=function(){window.localObject.btnClick()};"+ "document.body.appendChild(btn); "+ " })()"); } return super.onOptionsItemSelected(item); } /** * 本地javascript对象 */ class OnJavaScriptLocalObject { @JavascriptInterface public void btnClick() { AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this) .setMessage("这是android弹出的提示框哟") .setNegativeButton("确定",null) .setPositiveButton("取消",null); builder.create().show(); } } }

![](/wp-content/uploads/2015/03/20150322233629_12827.png)