Skip to content

Commit ac6b084

Browse files
antonisclaude
andauthored
feat(android): Connect traces with web content in a WebView (#6395)
* feat(android): Connect traces with web content in a WebView Add SentryWebViewTracing.addTracePropagation, which writes the current trace into pages from allowed hosts as sentry-trace and baggage meta tags before any page script runs, so @sentry/browser in the page continues the trace on pageload. It uses androidx.webkit's document-start script, a compileOnly dependency checked at runtime, and adds a sample screen and an instrumented test. Refs JAVA-716 Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * changelog Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * fix(android): Keep non-default ports and handle old androidx.webkit A WebView origin rule without a port only matches port 443, so a non-default port in an allowedHosts entry is now kept in the rule. androidx.webkit is compileOnly, so an app may ship an older version than the SDK was compiled against. A LinkageError is now caught, like for androidx.activity in the feedback form, and the call returns false. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * fix(android): Remove the previous WebView script after an off-thread call A call off the WebView's thread returns false without touching the WebView, which left Sentry's previous script installed. The removal is now posted to the WebView's thread, and skipped if a call on that thread replaced the script in the meantime. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * fix(android): Track WebView script replacements per WebView The off-thread cleanup compared against one counter shared by all WebViews, bumped before the replacement finished. A concurrent off-thread call could then remove a script that was just installed, and a call on another WebView cancelled this WebView's cleanup. The count is now kept per WebView, with weak keys, and bumped once the replacement is done. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * ref(samples): Move the WebView trace screen to the Tracing tab The sample no longer shows an iframe; the instrumented test in sentry-uitest-android still checks that iframes don't get the trace. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * fix(android): Match internationalized hosts in WebView trace propagation The page's location.hostname is in punycode, so an allowedHosts entry like münchen.de never matched. Non-ASCII entries are now converted with IDN.toASCII, and entries that cannot be converted are dropped. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * docs(changelog): Shorten WebView trace propagation entry Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * fix(android): Never throw from the posted WebView script removal Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * fix(android): Rethrow fatal errors from the posted WebView script removal Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * Add docs link to the changelog * Updated link to WebView documentation in CHANGELOG. --------- Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
1 parent f3a3bc4 commit ac6b084

23 files changed

Lines changed: 1757 additions & 0 deletions

File tree

‎CHANGELOG.md‎

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -9,6 +9,10 @@
99

1010
### Features
1111

12+
- Connect Android traces with web content in a `WebView` using `SentryWebViewTracing.addTracePropagation(webView, "example.com")` ([#6395](https://github.com/getsentry/sentry-java/pull/6395))
13+
- Requires the `androidx.webkit:webkit` dependency. Only list hosts whose content you control.
14+
- Call it on the main thread before each page load you want connected.
15+
- See the [WebView docs](https://docs.sentry.io/platforms/android/configuration/webview/) for details.
1216
- Monitor every Spring `@Scheduled` method with Sentry Crons by setting `sentry.monitor-scheduled-tasks=true`, without adding `@SentryCheckIn` to each method. Sentry creates each monitor from the method's `@Scheduled` schedule. Exclude methods with `sentry.exclude-scheduled-tasks` ([#6275](https://github.com/getsentry/sentry-java/pull/6275), [#6276](https://github.com/getsentry/sentry-java/pull/6276), [#6277](https://github.com/getsentry/sentry-java/pull/6277))
1317
- Quartz `SentryJobListener` can send a monitor config derived from the trigger with check-ins, so Sentry creates or updates the monitor from code. Set the `sentry-upsert-monitor-config` job or trigger data key to `"true"` to send the schedule ([#6216](https://github.com/getsentry/sentry-java/pull/6216))
1418
- Send a monitor config derived from Spring `@Scheduled` with `@SentryCheckIn` check-ins, so Sentry creates or updates the monitor from code. Set `@SentryCheckIn(upsertMonitorConfig = true)` to send the schedule ([#6215](https://github.com/getsentry/sentry-java/pull/6215))

‎gradle/libs.versions.toml‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -126,6 +126,7 @@ androidx-room-ktx = { module = "androidx.room:room-ktx", version.ref = "room2" }
126126
androidx-room-runtime = { module = "androidx.room:room-runtime", version.ref = "room2" }
127127
androidx-room3-compiler = { module = "androidx.room3:room3-compiler", version.ref = "room3" }
128128
androidx-room3-runtime = { module = "androidx.room3:room3-runtime", version.ref = "room3" }
129+
androidx-webkit = { module = "androidx.webkit:webkit", version = "1.14.0" }
129130
androidx-sqlite = { module = "androidx.sqlite:sqlite", version.ref = "sqlite" }
130131
androidx-sqlite-bundled = { module = "androidx.sqlite:sqlite-bundled", version.ref = "sqliteRc" }
131132
androidx-sqlite-framework = { module = "androidx.sqlite:sqlite-framework", version.ref = "sqliteRc" }
@@ -303,6 +304,7 @@ okhttp-mockwebserver = { module = "com.squareup.okhttp3:mockwebserver", version.
303304
okhttp-mockwebserver4 = { module = "com.squareup.okhttp3:mockwebserver", version = "4.9.2" }
304305
okhttp-tls = { module = "com.squareup.okhttp3:okhttp-tls", version.ref = "okhttp" }
305306
okio = { module = "com.squareup.okio:okio", version = "1.13.0" }
307+
rhino = { module = "org.mozilla:rhino", version = "1.8.0" }
306308
roboelectric = { module = "org.robolectric:robolectric", version = "4.15" }
307309

308310
[bundles]

‎sentry-android-core/api/sentry-android-core.api‎

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -628,6 +628,11 @@ public abstract interface class io/sentry/android/core/SentryUserFeedbackForm$Op
628628
public abstract fun configure (Landroid/content/Context;Lio/sentry/SentryFeedbackOptions;)V
629629
}
630630

631+
public final class io/sentry/android/core/SentryWebViewTracing {
632+
public static fun addTracePropagation (Landroid/webkit/WebView;Ljava/util/List;)Z
633+
public static fun addTracePropagation (Landroid/webkit/WebView;[Ljava/lang/String;)Z
634+
}
635+
631636
public class io/sentry/android/core/SpanFrameMetricsCollector : io/sentry/IPerformanceContinuousCollector, io/sentry/android/core/internal/util/SentryFrameMetricsCollector$FrameMetricsCollectorListener {
632637
protected final field lock Lio/sentry/util/AutoClosableReentrantLock;
633638
public fun <init> (Lio/sentry/android/core/SentryAndroidOptions;Lio/sentry/android/core/internal/util/SentryFrameMetricsCollector;)V

‎sentry-android-core/build.gradle.kts‎

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -104,6 +104,8 @@ dependencies {
104104
implementation(libs.androidx.core)
105105
// photo picker for user feedback screenshot attachments
106106
compileOnly(libs.androidx.activity)
107+
// document-start script injection for WebView trace propagation
108+
compileOnly(libs.androidx.webkit)
107109

108110
implementation(libs.epitaph)
109111

@@ -132,6 +134,8 @@ dependencies {
132134
testImplementation(projects.sentryAndroidNdk)
133135

134136
testImplementation(libs.androidx.activity.compose)
137+
testImplementation(libs.androidx.webkit)
138+
testImplementation(libs.rhino)
135139
testImplementation(libs.androidx.compose.ui)
136140
testImplementation(libs.androidx.compose.foundation)
137141
testImplementation(libs.androidx.compose.foundation.layout)

‎sentry-android-core/proguard-rules.pro‎

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -30,6 +30,12 @@
3030
-dontwarn androidx.activity.ComponentActivity
3131
-dontwarn androidx.activity.result.**
3232

33+
# androidx.webkit is a compileOnly dependency, used by WebView trace propagation
34+
# its presence is checked at runtime before use
35+
-dontwarn androidx.webkit.**
36+
# keep the name of the class the presence check looks up, so it still finds it in minified apps
37+
-keepnames class androidx.webkit.ScriptHandler
38+
3339
# To ensure that stack traces is unambiguous
3440
# https://developer.android.com/studio/build/shrink-code#decode-stack-trace
3541
-keepattributes LineNumberTable,SourceFile
Lines changed: 48 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,48 @@
1+
package io.sentry.android.core;
2+
3+
import android.webkit.WebView;
4+
import androidx.webkit.ScriptHandler;
5+
import androidx.webkit.WebViewCompat;
6+
import androidx.webkit.WebViewFeature;
7+
import java.util.Set;
8+
import org.jetbrains.annotations.NotNull;
9+
10+
/**
11+
* Installs Sentry's document-start script through androidx.webkit. All androidx.webkit references
12+
* are isolated in this class, so it must only be loaded once {@link SentryWebViewTracing} has
13+
* checked that androidx.webkit is available. That check deliberately lives outside of this class,
14+
* so that it can run without linking any androidx.webkit type.
15+
*/
16+
final class AndroidxWebViewScriptInstaller implements WebViewScriptInstaller {
17+
18+
@Override
19+
public boolean isDocumentStartScriptSupported() {
20+
return WebViewFeature.isFeatureSupported(WebViewFeature.DOCUMENT_START_SCRIPT);
21+
}
22+
23+
@Override
24+
public void removeInstalledScript(final @NotNull WebView webView) {
25+
final Object handler = webView.getTag(R.id.sentry_webview_trace_propagation);
26+
// Cleared first, so a handler whose removal throws is not removed again on every later call.
27+
webView.setTag(R.id.sentry_webview_trace_propagation, null);
28+
// A handler only exists if the feature was supported when it was installed.
29+
if (handler instanceof ScriptHandler
30+
&& WebViewFeature.isFeatureSupported(WebViewFeature.DOCUMENT_START_SCRIPT)) {
31+
((ScriptHandler) handler).remove();
32+
}
33+
}
34+
35+
@Override
36+
public boolean installScript(
37+
final @NotNull WebView webView,
38+
final @NotNull String script,
39+
final @NotNull Set<String> allowedOriginRules) {
40+
if (!WebViewFeature.isFeatureSupported(WebViewFeature.DOCUMENT_START_SCRIPT)) {
41+
return false;
42+
}
43+
final @NotNull ScriptHandler handler =
44+
WebViewCompat.addDocumentStartJavaScript(webView, script, allowedOriginRules);
45+
webView.setTag(R.id.sentry_webview_trace_propagation, handler);
46+
return true;
47+
}
48+
}
Lines changed: 255 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,255 @@
1+
package io.sentry.android.core;
2+
3+
import static io.sentry.util.IntegrationUtils.addIntegrationToSdkVersion;
4+
5+
import android.os.Build;
6+
import android.os.Handler;
7+
import android.os.Looper;
8+
import android.webkit.WebView;
9+
import androidx.annotation.MainThread;
10+
import io.sentry.BaggageHeader;
11+
import io.sentry.ILogger;
12+
import io.sentry.IScopes;
13+
import io.sentry.Sentry;
14+
import io.sentry.SentryLevel;
15+
import io.sentry.util.ExceptionUtils;
16+
import io.sentry.util.LoadClass;
17+
import io.sentry.util.TracingUtils;
18+
import java.util.Arrays;
19+
import java.util.Collections;
20+
import java.util.List;
21+
import java.util.Map;
22+
import java.util.WeakHashMap;
23+
import org.jetbrains.annotations.NotNull;
24+
import org.jetbrains.annotations.Nullable;
25+
26+
/**
27+
* Connects the app's trace with the trace of web content shown in a {@link WebView}.
28+
*
29+
* <p>{@link #addTracePropagation(WebView, List)} writes the current trace into every document the
30+
* WebView loads from an allowed host as {@code sentry-trace} and {@code baggage} meta tags, before
31+
* any page script runs. A {@code @sentry/browser} running in the page with {@code
32+
* browserTracingIntegration} then continues the trace on pageload.
33+
*
34+
* <p>Requires the {@code androidx.webkit:webkit} dependency and an Android System WebView that
35+
* supports {@code WebViewFeature.DOCUMENT_START_SCRIPT}.
36+
*/
37+
public final class SentryWebViewTracing {
38+
39+
static final @NotNull String SCRIPT_HANDLER_CLASS_NAME = "androidx.webkit.ScriptHandler";
40+
41+
private static final @NotNull String INTEGRATION_NAME = "WebViewTracePropagation";
42+
43+
/**
44+
* Counts, per WebView, the calls that finished replacing Sentry's script on the WebView's thread.
45+
* Weak keys, so it doesn't keep WebViews alive.
46+
*/
47+
private static final @NotNull Map<WebView, Long> replacements =
48+
Collections.synchronizedMap(new WeakHashMap<>());
49+
50+
private SentryWebViewTracing() {}
51+
52+
/**
53+
* Same as {@link #addTracePropagation(WebView, List)}.
54+
*
55+
* @param webView the WebView to connect
56+
* @param allowedHosts hosts whose pages receive the trace
57+
* @return true if the trace propagation script was installed
58+
*/
59+
@MainThread
60+
public static boolean addTracePropagation(
61+
final @NotNull WebView webView, final @NotNull String... allowedHosts) {
62+
return addTracePropagation(webView, Arrays.asList(allowedHosts));
63+
}
64+
65+
/**
66+
* Installs a script that writes the current trace into documents the WebView loads from an
67+
* allowed host. Call it on the main thread, before loading a URL: it applies to documents that
68+
* start loading after the call.
69+
*
70+
* <p>{@code allowedHosts} is a trust boundary: only list hosts whose content you control. A page
71+
* matches when its hostname equals an entry or is a subdomain of it, over https. Entries are
72+
* normalized, so a scheme, a path, and a trailing dot are ignored. A port other than 443 limits
73+
* the entry to pages served on that port (for example {@code "example.com:8443"}).
74+
*
75+
* <p>The trace is a snapshot taken when this is called. To propagate a newer trace to a later
76+
* page load, call this again: it replaces the script Sentry installed earlier and leaves other
77+
* scripts alone. If the call fails, no Sentry script is left on the WebView.
78+
*
79+
* <p>The root span name ({@code sentry-transaction}) is removed from {@code baggage}, as it is
80+
* free-form text that may carry user data.
81+
*
82+
* @param webView the WebView to connect
83+
* @param allowedHosts hosts whose pages receive the trace
84+
* @return true if the script was installed; false if androidx.webkit is missing, the WebView does
85+
* not support document-start scripts, {@code allowedHosts} has no valid entry, or there is no
86+
* trace (for example the SDK is not initialized), or it is called off the WebView's thread
87+
*/
88+
@MainThread
89+
public static boolean addTracePropagation(
90+
final @NotNull WebView webView, final @NotNull List<String> allowedHosts) {
91+
return addTracePropagation(webView, allowedHosts, Sentry.getCurrentScopes(), new LoadClass());
92+
}
93+
94+
static boolean addTracePropagation(
95+
final @NotNull WebView webView,
96+
final @NotNull List<String> allowedHosts,
97+
final @NotNull IScopes scopes,
98+
final @NotNull LoadClass loadClass) {
99+
// Registered on use rather than on success, like the other SDKs, so adoption counts apps that
100+
// wired the feature up even when this call cannot install.
101+
addIntegrationToSdkVersion(INTEGRATION_NAME);
102+
103+
if (!loadClass.isClassAvailable(SCRIPT_HANDLER_CLASS_NAME, scopes.getOptions())) {
104+
scopes
105+
.getOptions()
106+
.getLogger()
107+
.log(
108+
SentryLevel.WARNING,
109+
"WebView trace propagation requires the androidx.webkit dependency, skipping.");
110+
return false;
111+
}
112+
return install(webView, allowedHosts, scopes, new AndroidxWebViewScriptInstaller());
113+
}
114+
115+
static boolean install(
116+
final @NotNull WebView webView,
117+
final @NotNull List<String> allowedHosts,
118+
final @NotNull IScopes scopes,
119+
final @NotNull WebViewScriptInstaller installer) {
120+
final @NotNull ILogger logger = scopes.getOptions().getLogger();
121+
122+
// WebView methods throw when called off the WebView's thread; fail like any other misuse.
123+
if (!isOnWebViewThread(webView)) {
124+
logger.log(
125+
SentryLevel.WARNING,
126+
"addTracePropagation must be called on the WebView's thread, skipping WebView trace propagation.");
127+
removeOnWebViewThread(webView, installer, logger);
128+
return false;
129+
}
130+
131+
try {
132+
return replaceScript(webView, allowedHosts, scopes, installer, logger);
133+
} catch (LinkageError e) {
134+
// androidx.webkit is compileOnly, so the version in the app's apk may be older than the one
135+
// we compiled against and lack the APIs used here.
136+
logger.log(
137+
SentryLevel.WARNING,
138+
"androidx.webkit is too old for WebView trace propagation, skipping.",
139+
e);
140+
return false;
141+
} finally {
142+
// Counted once the replacement is done, so an off-thread call made while it runs doesn't
143+
// later remove the script it installed. Only written on the WebView's thread.
144+
replacements.put(webView, replacementsOf(webView) + 1);
145+
}
146+
}
147+
148+
private static boolean replaceScript(
149+
final @NotNull WebView webView,
150+
final @NotNull List<String> allowedHosts,
151+
final @NotNull IScopes scopes,
152+
final @NotNull WebViewScriptInstaller installer,
153+
final @NotNull ILogger logger) {
154+
// Remove Sentry's previous script first, so a failed re-add never leaves a stale trace behind.
155+
installer.removeInstalledScript(webView);
156+
157+
final @NotNull List<String> hosts = WebViewTracePropagationScript.normalizeHosts(allowedHosts);
158+
if (hosts.isEmpty()) {
159+
logger.log(
160+
SentryLevel.WARNING,
161+
"No valid allowedHosts provided, skipping WebView trace propagation.");
162+
return false;
163+
}
164+
165+
if (!installer.isDocumentStartScriptSupported()) {
166+
logger.log(
167+
SentryLevel.WARNING,
168+
"The WebView does not support document-start scripts, skipping WebView trace propagation.");
169+
return false;
170+
}
171+
172+
final @Nullable TracingUtils.TracingHeaders headers =
173+
TracingUtils.trace(scopes, null, scopes.getSpan());
174+
if (headers == null) {
175+
logger.log(
176+
SentryLevel.DEBUG,
177+
"No trace available (the SDK is disabled or not initialized), skipping WebView trace propagation.");
178+
return false;
179+
}
180+
181+
final @Nullable BaggageHeader baggageHeader = headers.getBaggageHeader();
182+
final @Nullable String baggage =
183+
WebViewTracePropagationScript.stripTransactionFromBaggage(
184+
baggageHeader == null ? null : baggageHeader.getValue());
185+
final @NotNull String script =
186+
WebViewTracePropagationScript.build(
187+
hosts, headers.getSentryTraceHeader().getValue(), baggage);
188+
189+
try {
190+
if (!installer.installScript(
191+
webView, script, WebViewTracePropagationScript.originRules(allowedHosts))) {
192+
logger.log(
193+
SentryLevel.WARNING,
194+
"The WebView does not support document-start scripts, skipping WebView trace propagation.");
195+
return false;
196+
}
197+
} catch (IllegalArgumentException e) {
198+
logger.log(
199+
SentryLevel.WARNING, "Invalid allowedHosts, skipping WebView trace propagation.", e);
200+
return false;
201+
}
202+
203+
return true;
204+
}
205+
206+
/**
207+
* A failed call must not leave a stale trace behind, but off the WebView's thread the script can
208+
* only be removed later, on that thread. The removal is skipped if a call on the WebView's thread
209+
* replaced this WebView's script in the meantime, so it never removes a newer script.
210+
*/
211+
private static void removeOnWebViewThread(
212+
final @NotNull WebView webView,
213+
final @NotNull WebViewScriptInstaller installer,
214+
final @NotNull ILogger logger) {
215+
final long replacementsSeen = replacementsOf(webView);
216+
new Handler(webViewLooper(webView))
217+
.post(
218+
() -> {
219+
if (replacementsOf(webView) != replacementsSeen) {
220+
return;
221+
}
222+
// Runs outside of any app call, so only fatal errors may escape: for example, the
223+
// WebView may have been destroyed since.
224+
try {
225+
installer.removeInstalledScript(webView);
226+
} catch (LinkageError e) {
227+
logger.log(
228+
SentryLevel.WARNING,
229+
"androidx.webkit is too old for WebView trace propagation, skipping.",
230+
e);
231+
} catch (Throwable e) {
232+
ExceptionUtils.rethrowIfFatal(e);
233+
logger.log(
234+
SentryLevel.WARNING,
235+
"Failed to remove the WebView trace propagation script.",
236+
e);
237+
}
238+
});
239+
}
240+
241+
private static long replacementsOf(final @NotNull WebView webView) {
242+
final @Nullable Long count = replacements.get(webView);
243+
return count == null ? 0 : count;
244+
}
245+
246+
private static boolean isOnWebViewThread(final @NotNull WebView webView) {
247+
return Looper.myLooper() == webViewLooper(webView);
248+
}
249+
250+
private static @NotNull Looper webViewLooper(final @NotNull WebView webView) {
251+
return Build.VERSION.SDK_INT >= Build.VERSION_CODES.P
252+
? webView.getWebViewLooper()
253+
: Looper.getMainLooper();
254+
}
255+
}

0 commit comments

Comments
 (0)