Android调用JS
首先要使能JS,添加mWebView.getSettings().setJavaScriptEnabled(true);
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
|
mWebView.setWebViewClient(new WebViewClientEmb());
public class WebViewClientEmb extends WebViewClient {
@Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
view.loadUrl(url);
}
@Override
public void onPageStarted(WebView view, String url, Bitmap favicon){
super.onPageStarted(view, url, favicon);
}
@Override
public void onPageFinished(WebView view, String url) {
super.onPageFinished(view, url);
mWebView.loadUrl("javascript:setShareInfo2()");
}
}
|
在onPageFinished方法中使用mWebView.loadUrl方法来调用JS方法,亲测有效。
JS调android
需要注意,在mWebView.addJavascriptInterface中药指定调用的名称,可随意定义,但js中必须和此处相同。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20
|
mWebView.addJavascriptInterface(new JavaScriptObject(this), "Android");
private class JavaScriptObject
Context mContxt;
public JavaScriptObject(Context mContxt) {
this.mContxt = mContxt;
}
@JavascriptInterface//android:targetSdkVersion>=17需要添加该注解
public void showToast(String toast){
Toast.makeText(mContxt, toast, Toast.LENGTH_SHORT).show();
}
@JavascriptInterfac
public void setShareInfo2(String title,String url){
Toast.makeText(mContxt, "setShareInfo2 title:" + title + " url:"+url, Toast.LENGTH_SHORT).show();
}
@JavascriptInterfa
public void setShareInfo(String title,String url){
Toast.makeText(mContxt, "setShareInfo title:" + title + " url:"+url, Toast.LENGTH_SHORT).show();
}
}
|
js测试网页:
http://lightsmeki.github.io/test/web/index.html
eclipse测试工程demo百度云下载:http://pan.baidu.com/s/1eRSxNUi 密码:427f