2

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 a web-page in the browser, I want the browser to notify the native application about the function-call/event. How can it be done??

hello512
  • 379
  • 4
  • 16

1 Answers1

1

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";
    }

}
Touhid
  • 1,556
  • 18
  • 18