Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to listen for javascript events from a native android application?

I have a native Android app that has a webView that loads a web page I have no control over.

In app I need to track/detect a “MessageEvent” that happens when a button is clicked on this page within the webView.

Scenario: User presses a button within the webView which fires off a "MessageEvent", When this “MessageEvent” is detected, a method in the Java/Kotlin code needs to be called, either through a listener that waits for this “MessageEvent” or another way(irrelevant how the method is called).

My main concern is how to detect this javascript “MessageEvent” event within my Java/Kotlin code.

like image 214
GNova Avatar asked Nov 25 '25 03:11

GNova


1 Answers

I found the solution that seems to have worked, it was posted on another Answer:

Using our webview implementation. We implemented the onPageFinished method in order to inject our JS code to load the web:

override fun onPageFinished(url: String?) {
webview.loadUrl(
"javascript:(function() {" +
    "window.parent.addEventListener ('message', function(event) {" +
    " Android.receiveMessage(JSON.stringify(event.data));});" +
    "})()"
)
}

what we are doing is creating a listener that sends those messages to our own JS and Android Bridge interface. Which we've previously created in the webview setup in our Android activity as we normally do with addJavascriptInterface.

webview.addJavascriptInterface(JsObject(presenter), "Android”)

This way, we already have that communication bridge and all the messages sent by the postMessage will reach us in that interface that is subscribed with that listener.

class JsObject(val presenter: Presenter) {
    @JavascriptInterface
    fun receiveMessage(data: String): Boolean {
        presenter.onDataReceived(data)
        Log.d("Data from JS", data)
        return true
    }

Original Answer: https://stackoverflow.com/a/62500309/7849477

Hope it helps someone else.

like image 113
GNova Avatar answered Nov 27 '25 15:11

GNova



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!