开发者

How to handle javascript events from a native android application?

I have a native android application using which, I want to track the javascript events and method calls while an HTML page runs in the browser on Android phone. So basically, whenever a function-call/event is triggerred in javascript on 开发者_如何学Pythona web-page in the browser, I want the browser to notify the native application about the function-call/event. How can it be done??


You can do it with your web view not browser:

HTML part (load this html page to your webView):

<!doctype html>
<html>
<body>
<div style="text-align:center; margin-top:50px">
    <h3>My Headding</h3>
    <button onclick="fireThisMethod('My message')" type="button">Click Me!</button>

</div>
</body>
<script type="text/javascript">

function fireThisMethod() {
   var msg = Android.getMsgFromJava();
   document.getElementsByTagName("h3")[0].innerText = msg;
   Android.sendJsMsgToWebView("Message to java");
}

</script>
</html>

Java WebView part, add below line after load webView url:

// JS interface
    webView.addJavascriptInterface(new JavaScriptInterface(this), "Android");

add below inner class:

public class JavaScriptInterface {
    Context context;

    JavaScriptInterface(Context context) {
        this.context = context;
    }

    @SuppressWarnings("unused")
    @JavascriptInterface
    public void sendJsMsgToWebView(String webMessage) {
        Toast.makeText(context, "Get from javascript web" + webMessage, Toast.LENGTH_SHORT).show();
    }

    @SuppressWarnings("unused")
    @JavascriptInterface
    public String getMsgFromJava() {
        return "Return from native java";
    }

}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜