Skip to main content

WebBridge (WebView)

Technical guide for integrating Adtrace WebBridge into an Android app that loads content in a WebView.

Aligned with Adtrace Android SDK / WebBridge v2.6.0.

For native-only apps (no WebView), see Getting started with the Android SDK.
For Trusted Web Activity, use the TWA documentation. Do not use WebBridge for TWA.

Example app: example-app-webbridge.
JS assets: WebBridge plugin assets.

1. Overview

The WebBridge lets HTML/JavaScript in a WebView talk to the same native Adtrace SDK used by Android code.

One SDK instance

There is only one SDK instance per app process. Initialize it once, either from JavaScript or from native Android, never both.

Calling onCreate twice logs: AdTrace already initialized.

2. Choose your integration case

Ask one question: Do you already track Adtrace events from Android native code (Activity / Application / Service)?

Case A: WebBridge-onlyCase B: Hybrid
Native events?No. Tracking only from HTML/JSYes. Activities/Services already call AdTrace.trackEvent
Who calls AdTrace.onCreate?JavaScript in the WebView pageNative (Application / early Activity)
Native Application init?Optional / not required for AdtraceRequired
JS AdTrace.onCreate?Yes (after bridge is registered)No. Skip it
Native AdTrace.trackEvent?Not usedYes
JS AdTrace.trackEvent?YesYes (same SDK)
Typical appIn-app browser / mostly HTML funnelMixed native UI + WebView screens

3. Shared setup (both cases)

Complete core SDK setup (Maven / AAR, Google Play Services, Install Referrer) as needed in Getting started with the Android SDK. Then add the WebBridge plugin below.

Requirements

ItemRequirement
minSdkVersion17 (Web Bridge)
Core SDKio.adtrace:android-sdk (same version as webbridge)
Pluginio.adtrace:android-sdk-plugin-webbridge
WebViewJavaScript enabled
PermissionsINTERNET, ACCESS_NETWORK_STATE, AD_ID (API 31+)
Google Playplay-services-ads-identifier + installreferrer recommended

Gradle

build.gradle
dependencies {
implementation 'io.adtrace:android-sdk:2.6.0'

// Add the following if you are using the Adtrace SDK inside web views on your app
implementation 'io.adtrace:android-sdk-plugin-webbridge:2.6.0'

implementation 'com.android.installreferrer:installreferrer:2.2'
implementation 'com.google.android.gms:play-services-ads-identifier:18.0.0'
}

You can also download the WebBridge AAR/JAR from the GitHub releases page.

Important

The minimum supported Android API level for the WebBridge plugin is 17 (Jelly Bean). Do not use WebBridge for TWA apps.

Permissions

<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="com.google.android.gms.permission.AD_ID" />

JavaScript assets

Shipped by the webbridge plugin (merged into the APK):

FileRole
adtrace.jsMain AdTrace JS API
adtrace_config.jsAdTraceConfig
adtrace_event.jsAdTraceEvent
adtrace_third_party_sharing.jsThird-party sharing helper

Include order:

<script src="adtrace_event.js"></script>
<script src="adtrace_third_party_sharing.js"></script>
<script src="adtrace_config.js"></script>
<script src="adtrace.js"></script>

For remote HTML, host these files next to your page (or use absolute URLs). See WebBridge JS files.

Connect your WebView

This step is required for both Case A and Case B. Do it in the Activity that hosts the WebView.

Before you start, get a reference to your WebView object. Then:

  1. Call webView.getSettings().setJavaScriptEnabled(true) to enable JavaScript in the WebView.
  2. Start the default AdTraceBridge instance with AdTraceBridge.registerAndGetInstance(getApplication(), webView). This registers the Adtrace bridge as a JavaScript interface on the WebView.
  3. Call AdTraceBridge.setWebView() if you need to attach a different WebView later.
  4. Call AdTraceBridge.unregister() in onDestroy to unregister the bridge and WebView.
Important

Call AdTraceBridge.registerAndGetInstance before webView.loadUrl(...). Otherwise JavaScript cannot see AdTraceBridge.

After these steps, your activity should look like this:

WebViewActivity.java
public class WebViewActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_webview);

WebView webView = findViewById(R.id.webView);
webView.getSettings().setJavaScriptEnabled(true);
webView.setWebChromeClient(new WebChromeClient());
webView.setWebViewClient(new WebViewClient());

AdTraceBridge.registerAndGetInstance(getApplication(), webView);
webView.loadUrl("file:///android_asset/your-page.html");
}

@Override
protected void onDestroy() {
AdTraceBridge.unregister();
super.onDestroy();
}
}

Set up Proguard

If you are using Proguard, add these lines to your Proguard file:

proguard-rules.pro
-keep class io.adtrace.sdk.** { *; }
-keep class io.adtrace.sdk.webbridge.** { *; }
-keep class com.google.android.gms.common.ConnectionResult {
int SUCCESS;
}
-keep class com.google.android.gms.ads.identifier.AdvertisingIdClient {
com.google.android.gms.ads.identifier.AdvertisingIdClient$Info getAdvertisingIdInfo(android.content.Context);
}
-keep class com.google.android.gms.ads.identifier.AdvertisingIdClient$Info {
java.lang.String getId();
boolean isLimitAdTrackingEnabled();
}
-keep public class com.android.installreferrer.** { *; }

If you are not publishing your app in the Google Play Store, use the following io.adtrace.sdk package rules:

proguard-rules.pro
-keep public class io.adtrace.sdk.** { *; }

4. Case A: WebBridge-only (no native events)

Use Case A when your Android app loads content in a WebView and all Adtrace tracking (init, sessions, events) runs from HTML/JavaScript.

This is not Trusted Web Activity (TWA). For TWA, follow the TWA documentation instead.

On the native side you only:

  1. Host the WebView
  2. Register AdTraceBridge before loading the page

You do not call native AdTrace.onCreate or native AdTrace.trackEvent.

Native side (bridge only)

No Application Adtrace init. No native trackEvent.

Register the bridge as described in Connect your WebView, then load your HTML page. You do not need android:name=".GlobalApplication" for Adtrace in Case A.

JavaScript side (init)

Load the WebBridge scripts, create AdTraceConfig, then call AdTrace.onCreate once:

<script src="adtrace_event.js"></script>
<script src="adtrace_third_party_sharing.js"></script>
<script src="adtrace_config.js"></script>
<script src="adtrace.js"></script>

<script>
var config = new AdTraceConfig(
'{YourAppToken}',
AdTraceConfig.EnvironmentSandbox
);
AdTrace.onCreate(config);
</script>

Replace {YourAppToken} with your app token from the Adtrace panel.

Use AdTraceConfig.EnvironmentSandbox while testing and AdTraceConfig.EnvironmentProduction before release.

How to use Adtrace features from JavaScript

Do not duplicate feature examples on this page. For each Adtrace feature, open that feature’s Android docs page and select the Javascript tab.

What you wantOpen this pageThen
Log levelSet log levelChoose Javascript
Delay start / event buffering / offline / disableConfigurationOpen the feature page → Javascript
Track events, revenue, parametersEvent trackingChoose Javascript
Session parametersSession parametersChoose Javascript
Device IDsDevice IDsChoose Javascript
Callbacks / attributionSend callback information · User attributionChoose Javascript

Pattern for developers and tools:

  1. Find the feature under Android Configuration, Event tracking, or Additional features.
  2. Open the page for that feature.
  3. Select the Javascript tab.
  4. Copy the JS sample into your WebView HTML (after Case A AdTrace.onCreate, or in Case B without a second onCreate).
tip

In Case A, set config options and callbacks on AdTraceConfig before AdTrace.onCreate. In Case B, set the same options on the native AdTraceConfig instead.

Case A order of operations

  1. Enable JavaScript on WebView
  2. AdTraceBridge.registerAndGetInstance(application, webView)
  3. loadUrl(...)
  4. HTML loads adtrace*.js
  5. JS: AdTrace.onCreate(config) once
  6. Use feature pages (Javascript tab) for events, log level, callbacks, and other APIs
  7. Activity onDestroyAdTraceBridge.unregister()

Case A checklist

  • Dependencies: core SDK + webbridge plugin
  • Permissions: INTERNET, ACCESS_NETWORK_STATE, AD_ID
  • Bridge registered before page load
  • JS calls AdTrace.onCreate once
  • Native code does not call AdTrace.onCreate
  • Logcat tag:AdTrace shows install/session after page load

5. Case B: Hybrid (native events + Web Bridge)

Use when Android native code already (or also) tracks events, and WebView HTML should track more events into the same SDK.

Complete shared setup first, then initialize on native as in Getting started with the Android SDK.

Step B1: Initialize on native side (once)

GlobalApplication.java
public class GlobalApplication extends Application {
@Override
public void onCreate() {
super.onCreate();

AdTraceConfig config = new AdTraceConfig(
this,
"{YourAppToken}",
AdTraceConfig.ENVIRONMENT_SANDBOX);
config.setLogLevel(LogLevel.VERBOSE);
config.setSendInBackground(true);
// Set native callbacks here if you need them:
// config.setOnEventTrackingSucceededListener(...);

AdTrace.onCreate(config);
registerActivityLifecycleCallbacks(new AdTraceLifecycleCallbacks());
}
}
<application android:name=".GlobalApplication" ...>

Complete native install referrer, Google Play Services, and session tracking as in Getting started with the Android SDK.

Step B2: Track events from native code

AdTraceEvent event = new AdTraceEvent("{eventToken}");
AdTrace.trackEvent(event);

Step B3: Register Web Bridge (no second init)

Register the bridge as described in Connect your WebView. The bridge connects JS to the already running native SDK. Do not call AdTrace.onCreate again from JavaScript.

Step B4: Track from JavaScript (skip onCreate)

Load the WebBridge scripts. Do not call AdTrace.onCreate (native already did).

For events and other features, use the Javascript tab on each feature page. See How to use Adtrace features from JavaScript.

Minimal pattern:

<script src="adtrace_event.js"></script>
<script src="adtrace_config.js"></script>
<script src="adtrace.js"></script>
<script>
// Do NOT call AdTrace.onCreate. Native already did.
// Track / configure using JS samples from each feature page.
</script>

What belongs where (Case B)

ConcernNative AndroidJavaScript (bridge)
AdTrace.onCreate + session lifecycleYesNo
Events from Activities / ServicesYes
Events from HTML / web funnelsYes
Callbacks / log levelOn native AdTraceConfigOnly if you used Case A
Install referrer / Play depsYes
Deep links from IntentAdTrace.appWillOpenUrl(uri, context)AdTrace.appWillOpenUrl(url) if page has URL

Case B checklist

  • One native AdTrace.onCreate (Application recommended)
  • Same app token / environment everywhere
  • Native events via io.adtrace.sdk.AdTrace / AdTraceEvent
  • Bridge registered before loading HTML
  • HTML does not call AdTrace.onCreate
  • HTML still calls AdTrace.trackEvent (and other JS APIs) as needed
  • AdTraceBridge.unregister() in WebView Activity onDestroy

6. JavaScript features (use feature pages)

After the SDK is started (JS onCreate in Case A, or native onCreate in Case B), use Adtrace features from the matching Android docs page.

When to call AdTrace.onCreate from JS

CaseCall JS AdTrace.onCreate?
A: WebBridge-onlyYes
B: HybridNo

Where to find JS examples

For each feature:

  1. Open the Android feature page (Configuration, Event tracking, Additional features, Deep linking).
  2. Select the Javascript tab.
  3. Copy the sample into your WebView HTML.

See How to use Adtrace features from JavaScript for a feature → page map.

Examples:

In Case A, apply config setters and callbacks on AdTraceConfig before AdTrace.onCreate.
In Case B, apply the same options on the native AdTraceConfig; JS callback setters on config have no effect if JS never calls onCreate.

SourceAPI
URL known in HTMLAdTrace.appWillOpenUrl(deeplinkUrl)
Android Intent dataNative AdTrace.appWillOpenUrl(uri, context)

See also Deep linking and Reattribution.

Install referrer

Configure Play Install Referrer on the native side for both cases. See Getting started: Add Install Referrer.

Privacy

For GDPR, third-party sharing, measurement consent, COPPA, and Kids apps, open the matching Android feature page and use the Javascript tab. COPPA / Kids options belong on the config that performs onCreate (JS in Case A, native in Case B).

WebView recreation

AdTraceBridge.setWebView(newWebView);

Remote HTML

  1. Host adtrace*.js with your page
  2. Register bridge before loadUrl
  3. Follow Case A or B rules for onCreate

8. Verification and troubleshooting

Success checks

Both cases

  • Bridge registered before page load
  • JS enabled; adtrace*.js load without 404
  • Logcat adb logcat -s AdTrace shows traffic
  • Tracked event shows Path: /event

Case A only

  • JS AdTrace.onCreate runs after bridge registration
  • No native AdTrace.onCreate

Case B only

  • Native AdTrace.onCreate in Application
  • Native event appears when tapping native UI
  • HTML does not call AdTrace.onCreate
  • No log line AdTrace already initialized from a second onCreate

Common issues

SymptomLikely causeFix
AdTrace already initializedBoth native and JS called onCreatePick Case A or B. Only one onCreate
AdTraceBridge undefined in JSBridge after loadUrl, or wrong WebViewRegister before load
No events from HTML (Case B)Forgot bridge registrationCall registerAndGetInstance
No events from native (Case B)SDK never startedAdd native AdTrace.onCreate
No events from HTML (Case A)Forgot JS onCreateCall AdTrace.onCreate in page
Scripts 404Remote page without JS assetsHost adtrace*.js
minSdk errorsAPI < 17Raise minSdk for webbridge

9. API reference

Native: AdTraceBridge

MethodDescription
registerAndGetInstance(Application, WebView)Register JS interface
getDefaultInstance()Get singleton
setWebView(WebView)Rebind WebView
setApplicationContext(Application)Update context
unregister()Tear down bridge

Native: core SDK (Case B)

Use io.adtrace.sdk.AdTrace, AdTraceConfig, and AdTraceEvent as in Getting started with the Android SDK.

JavaScript: AdTrace

MethodDescription
onCreate(config)Init SDK (Case A only)
trackEvent(event)Track event
trackAdRevenue(source, payload)Ad revenue
onResume / onPauseManual session hooks
setEnabled / isEnabledEnable flag
appWillOpenUrlDeep link
setReferrerReferrer string
setOfflineModeOffline queue
sendFirstPackagesEnd delay-start
add/remove/resetSession*Parameter(s)Session params
setPushTokenFCM token
gdprForgetMe / disableThirdPartySharingPrivacy
trackThirdPartySharing / trackMeasurementConsentConsent
getGoogleAdId / getAmazonAdId / getAdidDevice IDs
getAttribution / getSdkVersionAttribution / version
teardownTear down JS/native bridge state

JavaScript: AdTraceConfig / AdTraceEvent

Use each feature page’s Javascript tab. See How to use Adtrace features from JavaScript. Full setters also match adtrace_config.js / adtrace_event.js in the plugin assets.