android webview and javascript交互

方法一:

*javascript in html:

<SCRIPT  LANGUAGE="JavaScript">

function checkOrientation(){
 alert(window.orientation);
};

window.addEventListener('onorientationchange' in window ? 'orientationchange' : 'resize', checkOrientation, false);

function print() {
 window.location="print://print";
};

function setting() {
 window.location="setting://setting";
};

</SCRIPT>

*java code:
        public boolean shouldOverrideUrlLoading(WebView view, String url) {

            AppUtils.LogD(url);

            if (url.startsWith("mailto:")) {
                MailTo mt = MailTo.parse(url);
                Intent i = AppUtils.newEmailIntent(activity, mt.getTo(),
                        mt.getSubject(), mt.getBody(), mt.getCc());
                activity.startActivity(i);
                view.reload();
                return true;
            } else if (url.startsWith("print://print")) {

                // show toast message for print button
                Toast.makeText(activity, R.string.print_button_alert,
                        Toast.LENGTH_LONG).show();
                return true;

            } else if (url.startsWith("setting://setting")) {

                // show setting dialog
                ((DetailViewControlerImpl) activity).openSettingsPage();
                return true;
            } else {
                return false;
            }
        }

方法二:

javascript in html(mypage):

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<HTML>
<HEAD>
<TITLE>Actuate Viewer</TITLE>
<script type="text/javascript">
    function change() {
        document.getElementById("changePhoto").src = "/wp-content/images1/20181012/20120519094025145371.png";
    }
</script>
</HEAD>

<BODY>
 
    <a onclick="window.mypage.clickOnAndroid()"> <img id="changePhoto"
        src="/wp-content/images1/20181012/20120519094025304372.png" /><br> Click me! </a>
</BODY>
</HTML>

java code:

    mWebView.addJavascriptInterface(new MyJavaScriptInterface(), "mypage");

    final class MyJavaScriptInterface {
        public MyJavaScriptInterface() {

        }

        public void clickOnAndroid() {
            mHandler.post(new Runnable() {

                @Override
                public void run() {

                    mWebView.loadUrl("javascript:change()");
                }
            });
        }
    }

 

 

摘自 fhy_2008的專欄

發佈留言