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??

1 Answer 1

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

}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.