android中js与java的相互调用

webView = (WebView)this.findViewById(R.id.webView);  

        //设置字符集编码  

        webView.getSettings().setDefaultTextEncodingName("UTF-8");  

        //开启JavaScript支持  

        webView.getSettings().setJavaScriptEnabled(true);  

        

        class JsObject {

            @JavascriptInterface

            public String toString() { return "hehe"; }

         }

        webView.addJavascriptInterface(new JsObject(), "hehe"); 

        webView.loadData("", "text/html", null);

        // 支持alert

        webView.setWebChromeClient(new WebChromeClient() {  

            @Override  

            public boolean onJsAlert(WebView view, String url, String message, final JsResult result) {  

                AlertDialog.Builder b2 = new AlertDialog.Builder(HTMLActivity.this)  

                        .setMessage(message)  

                        .setPositiveButton("ok",  

                                new AlertDialog.OnClickListener() {  

                                    @Override  

                                    public void onClick(DialogInterface dialog,  

                                            int which) {  

                                        result.confirm();  

                                    }  

                                });  

          

                b2.setCancelable(false);  

                b2.create();  

                b2.show();  

                return true;  

            }  

        });

webView.setWebViewClient(new WebViewClient());

        

        webView.getSettings().setJavaScriptCanOpenWindowsAutomatically(true);

try{

        Thread.currentThread().sleep(1000L);

        webView.loadUrl("javascript:alert(window.hehe.toString())");  

        }catch(Exception e){

       

        }

猜你喜欢

转载自shuechaolau.iteye.com/blog/2000112