ก๊วนซอฟท์แวร์ </softganz> SoftGang (Gang Software)

Web &amp; Software Developer Gang.

ทำให้ Web App คุยกับ Android ผ่านทาง WebView - Building Web Apps in WebView

by Little Bear @30 ม.ค. 61 12:00 ( IP : 171...72 ) | Tags : Android , Android App , Web App

Enabling JavaScript

JavaScript is disabled in a WebView by default. You can enable it through the WebSettings attached to your WebView. You can retrieve WebSettings with getSettings(), then enable JavaScript with setJavaScriptEnabled().

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

Binding JavaScript code to Android code

public class WebAppInterface {
    Context mContext;

    /** Instantiate the interface and set the context */
    WebAppInterface(Context c) {
        mContext = c;
    }

    /** Show a toast from the web page */
    @JavascriptInterface
    public void showToast(String toast) {
        Toast.makeText(mContext, toast, Toast.LENGTH_SHORT).show();
    }
}

Bind class Android

WebView webView = (WebView) findViewById(R.id.webview);
webView.addJavascriptInterface(new WebAppInterface(this), "Android");

Coding in javascript

<a href="javascript:void(0)" onclick="showAndroidToast('Hello Android!')">Click for android</a>
<script type="text/javascript">
function showAndroidToast(toast) {
    if (typeof Android=="object") Android.showToast(toast);
    else console.log("App not run on Android")
}
</script>



ที่มา Building Web Apps in WebView

Relate topics