如何在Android 4.2中调用JavaScript

时间:2013-02-08 11:53:32

标签: javascript android

我已经找到了很多关于如何从android调用JavaScript的例子。但这对我不起作用。我的目标SDK是17(android 4.2)。这是我从我的活动加载我的html页面的方式:

protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_test);

    myWebView = (WebView)findViewById(R.id.mapwebview1);
    WebSettings webSettings = myWebView.getSettings();
    webSettings.setJavaScriptEnabled(true);

    JavaScriptHandler jScriptHandler = new JavaScriptHandler(this); 
    WebChromeClient myWebChromeClient = new WebChromeClient();
    myWebView.setWebChromeClient(myWebChromeClient);
    myWebView.addJavascriptInterface(jScriptHandler, "MyHandler");

    myWebView.loadUrl("file:///android_asset/mywebpage.html");
    myWebView.loadUrl("javascript:myFunc()");


}

以下是我的JavaScriptHandler的代码:

public class JavaScriptHandler {
//TabFragmentMap mapFragment;
Context context;
//Fragment fragment;

public JavaScriptHandler (Context c){
    this.context = c;
}

}

以下是我的html的代码:

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<title>PhoneGap</title>
</head>
<body onload="myFunc()">
<h1 id="test1">Hello World</h1>
<input type="button" value="Say hello" onClick="moveMyself()" />
<div id="myDiv"></div>
<script type="text/javascript"> 


    function myFunc()
    {

       document.getElementById('test1').innerHTML = 'Good Morning';

    }

</script>
</body>
</html>

3 个答案:

答案 0 :(得分:2)

试试这个:

final WebView webview = (WebView)findViewById(R.id.browser);  
/* JavaScript must be enabled if you want it to work, obviously */  
webview.getSettings().setJavaScriptEnabled(true);  

/* WebViewClient must be set BEFORE calling loadUrl! */  
webview.setWebViewClient(new WebViewClient() {  
    @Override  
    public void onPageFinished(WebView view, String url)  
    {  
        webview.loadUrl("javascript:(function() { " +  
                "document.getElementsByTagName('body')[0].style.color = 'red'; " +  
                "})()");  
    }  
});  

webview.loadUrl("http://code.google.com/android");  

答案 1 :(得分:2)

实际上,Tamilarasi给了我同样的东西。如果有人想从html调用现有的JavaScript函数,请执行以下操作:

myWebView.setWebViewClient(new WebViewClient() {
        public void onPageFinished(WebView view, String url){
            myWebView.loadUrl("javascript:myFunc()");
        }
});
myWebView.loadUrl("file:///android_asset/myHtml.html");

答案 2 :(得分:-1)