Android webView get javascript web value

用法很簡單,功能上也比起iOS所能提供得支援強大,廢話不多說往下看。

JS呼叫Android

JS
function androidResponse() {
window.YOURNAME.FUNCTIONNAME("I am being sent to Android.");
}

Android
final class IJavascriptHandler {
IJavascriptHandler() {}
public void FUNCTIONNAME(String text) {
// this is called from JS with passed value
Toast t = Toast.makeText(getApplicationContext(), text, 2000);
t.show();
}
}


WebView記得要去設定一下
webView.addJavascriptInterface(new IJavascriptHandler(), "YOURNAME");




Android呼叫JS

JS
funcrion androidResponse(string){
alert(string)
}

Android
webView.loadUrl("javascript:androidResponse();");

webView記得去把JS enable
webview.getSettings().setJavaScriptEnabled(true);
或用
WebView myWebView = (WebView) findViewById(R.id.webview);
WebSettings webSettings = myWebView.getSettings();
webSettings.setJavaScriptEnabled(true);



update 2012-08-16
熊熊發現到Android Developer官方就有篇教學
http://developer.android.com/guide/webapps/webview.html

相關連結
Android Developer
Android Developer - WebView

沒有留言:

張貼留言