androidkotlinandroid-webviewandroid-instrumentation

How to get the current webview object in Android?


I am using Datadog to track user activity in my app. Now I need to instrument webviews. After initializing datadog's sdk , its documentation says that I have to call the following code snippet:

DatadogEventBridge.setup(webView)

that is, I have to call the static method setup and pass to it a WebView object. But the problem is: my application has many objects like this (many webviews). Do I have to put this code in every class that has a WebView attribute? Or is it possible in somehow use a callback function which is called whenever a webview is instatiated, the in this callback I'd call DatadogEventBridge.setup(webView)?

I tried using lifecycle callbacks and then receive an Acitivty for every "onResume" method in order to check whether this activity has a webview. But it went wrong.


Solution

  • I'm not really familiar with the Datadog Sdk but you could try creating your own WebView by extending the standard one - and then replace all the other WebViews with it. Here's how it'll look like in practice:

    class TrackableWebView : WebView {
    
        constructor(context: Context) : super(context)
    
        constructor(context: Context, attrs: AttributeSet?) : super(context, attrs)
    
        constructor(context: Context, attrs: AttributeSet?, defStyleAttr: Int)
            : super(context, attrs, defStyleAttr)
    
        init {
            DatadogEventBridge.setup(this)
        }
    }
    

    I think we can assume that the Sdk will be initialized much earlier than the WebViews, so there should be no problem with calling the DatadogEventBridge.setup(this) before the Sdk is initialized.

    Then if you use the XML layouts you just replace standard WebView with your custom one:

    <com.example.TrackableWebView
        android:layout_width="match_parent"
        android:layout_height="match_parent"/>