我用html和javascript开发了gui。我想在我的webview中加载它并在调用URL时调用javascript函数。我写了以下代码。但我的javascript函数根本没有被调用。我尝试了各种选择。请帮忙。
public class HelloWebView extends Activity {
WebView webview;
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
webview = (WebView) findViewById(R.id.webview);
webview.getSettings().setJavaScriptEnabled(true);
webview.getSettings().setJavaScriptCanOpenWindowsAutomatically(true);
webview.getSettings().setPluginState(PluginState.ON);
webview.getSettings().setDomStorageEnabled(true);
webview.addJavascriptInterface(new JavaScriptHandler(this), "Android");
webview.loadUrl("file:///android_asset/index.html");
webview.setWebViewClient( new WebViewClient() {
public boolean shouldOverrideUrlLoading(WebView view, String url) {
System.out.println( "shouldOverrideUrlLoading [" + url + "]" );
webview.loadUrl( "javascript:sendData()" );
return true;
}
public void onPageFinished(WebView view, String url) {
System.out.println( "onPageFinished [" + url + "]" );
webview.loadUrl( "javascript:function sendData(){}" );
}
});
webview.setWebChromeClient(new WebChromeClient() {
@Override public boolean onJsAlert(WebView view, String url, String message, JsResult result) {
/* Do whatever you need here */
return super.onJsAlert(view, url, message, result);
}
});
}
public class JavaScriptHandler {
Context mContext;
public JavaScriptHandler(Context context) {
mContext = context;
}
@JavascriptInterface
public void returnResult() {
}
}
}
使用Javascript:
sendData : function()
{
alert("Inside SendData()");
if( this.sendQueue.length > 0 )
{
var url = this.sendQueue[0];
this.sendQueue.splice( 0, 1 );
window.location = url;
}
}