Web Application Integration¶
After you complete the configuration on this page, the Browser RUM SDK automatically collects page Views, resource requests, frontend errors, and user actions, and reports the data to Guance.
For WebView pages in an App, first read WebView Page Integration, and choose an initialization method based on the page's scope of use.
For first-time integration, first complete Define Application → Select Integration Method → Integration Configuration in the console, then verify data reporting. After basic data reporting succeeds, you can adjust sampling, distributed tracing, and Session Replay as needed.
Define Application¶
- Go to RUM > Application List, click Create Application, and select Web as the application type.
- In Define Application, enter the application name and application ID. After the application is created, the system automatically generates a Client Token for client-side data reporting.
- In Select Integration Method, choose one method from the table below, then complete the corresponding operations in Integration Configuration.
For an existing application, you can go directly to its configuration page, verify the application information, and then continue the integration.
Select Integration Method¶
| Integration Method | Use Cases | Entry Point |
|---|---|---|
| Agent Automatic Integration | Want a coding assistant to analyze the project and complete SDK integration | Copy the prompt generated by the console and give it to the coding assistant in the application code repository for execution |
| Manual Integration | Want to modify business code yourself, choose how to import the SDK, and configure parameters | First choose a data reporting method, then integrate the SDK according to the application type |
| Server Automatic Integration | Host a website with Nginx or IIS and want to inject the SDK through the server | Configure collection parameters in the console and run the integration command on the target server |
Choose one integration method per page. For pages that already have the RUM SDK, first verify the existing configuration to avoid duplicate initialization or duplicate collection.
Agent Automatic Integration¶
- On the application configuration page, select Agent Automatic Integration.
- Copy the complete prompt in Integration Configuration. It contains integration information such as the current application ID, DataWay address, and temporary authorization code.
- Open the coding assistant in the application code repository and paste the prompt. The Agent analyzes the project structure according to the integration guide, reuses existing configuration, and completes the required SDK integration and verification.
- Follow Verify Integration to check actual data reporting and ingestion.
The integration guide in the prompt describes the runtime environment and specific steps. If integration information is not ready, handle it as follows:
- Personal API Key not generated: Click Generate API Key, then copy the prompt again after completion. If you do not have the corresponding permissions, contact the Workspace administrator to enable them.
- Temporary authorization code not ready: You can first have the Agent analyze the project, then continue the integration after completing the necessary information.
Manual Integration¶
Manual integration consists of two steps: first choose a data reporting method, then choose an SDK import method such as NPM or CDN.
| Data Reporting Method | Recommended Use Cases | Initialization Parameters |
|---|---|---|
| Use public DataWay | Usually the preferred choice; Guance provides the data receiving service | applicationId, site, clientToken |
| Local environment deployment | You need to deploy and manage DataKit yourself, or the current Workspace does not provide a public DataWay address | applicationId, datakitOrigin |
Choose only one of the two reporting methods. site and clientToken are used for public DataWay, while datakitOrigin is used for local environment deployment. Do not fill in both in the same initialization configuration.
Prepare Reporting Configuration¶
- Under Manual Integration, select Use Public DataWay.
- Copy
applicationId,site, andclientTokenfrom the current application's integration configuration. Use the current site address provided by the console. Do not use the console login address or an address from another site assite. - When integrating the SDK, keep the following configuration. You do not need to install DataKit or separately configure the RUM collector.
- Install DataKit and enable the RUM collector.
- Ensure that the network where user browsers are located can access the DataKit data reporting address, and install the IP geolocation database as needed to resolve the geolocation corresponding to user IPs.
- Under Manual Integration, select Local Environment Deployment, and configure
datakitOriginas the actual DataKit receiving address. HTTPS pages should use an accessible HTTPS receiving address to prevent requests from being blocked by the browser. - When integrating the SDK, remove
siteandclientTokenand use the following configuration instead.
Server Automatic Integration¶
Inject the RUM SDK into website HTML pages through Nginx or IIS without modifying application code. However, you need configuration and command execution permissions on the target server.
Prerequisites¶
- A Web application has been created, and you have configuration and command execution permissions on the target server.
- The page contains an injectable
<head>tag; keep only one RUM SDK integration method on the same page to avoid duplicate collection. - Browsers can access SDK resources and the data reporting address; when using CSP, configure the allowed scope according to the CSP Security Policy.
| Server | Environment Requirements and Operational Impact |
|---|---|
| Nginx | Linux Nginx 1.9.4+, http_sub_module, Bash, and curl; run as root or with sudo. Changes to the integration configuration reload Nginx |
| IIS | 64-bit Windows, IIS 7.5+, URL Rewrite 2.x, static resource read permissions, and a dedicated application pool; run PowerShell 5.1+ as administrator. Enabling, disabling, updating, and rolling back recycle the application pool, and in-process sessions may be lost |
Configure Integration¶
- In Select Integration Method on the Web application configuration page, select Server Automatic Integration.
- In Connect Application, select OpenWay or DataKit, and verify the reporting address, service name, environment, and application version. The application version is used to mark the business version and does not upgrade the SDK.
- In SDK Source and Loading, verify the resource source and loading method.
- In Collection Content, set the session sampling rate, error session compensation sampling rate, and user interaction collection. Enable Session Replay as needed, and configure the replay sampling rate, error replay compensation sampling rate, and privacy level. Replay first passes through session sampling, then replay sampling.
- In Installation Environment, select Nginx or IIS and read the current environment requirements; expand Advanced Integration Settings as needed.
- In Run Installation Command, copy the command generated from the current configuration and run it on the target server. When using automatic site discovery, select the site to integrate according to the terminal prompts.
The command already contains the configuration, so you do not need to download files separately. If you need to keep a record or update manually, you can download rumable.toml. The command and configuration contain the Client Token, so keep them secure.
Verify and Update¶
After running the command, first check the server execution result, then follow Verify Integration to confirm that the SDK on the website is running properly and data has been ingested. A successful installation or an HTTP 200 page response alone does not prove that data collection is successful.
If no data is received, check whether the enabled site and path were accessed, whether the SDK is blocked by CSP, whether the reporting address is reachable, and whether the session was sampled. If the page already integrates the SDK through NPM or CDN, resolve the duplicate integration first.
After modifying collection parameters, regenerate the integration command and run it on the target server. Saving or copying the configuration in the console only does not automatically update the injection configuration on the server; after modifying the downloaded rumable.toml, you also need to reapply it on the server.
For SDK parameter meanings, see Parameter Configuration; for sampling rules, see Sampling Configuration.
Manually Integrate the SDK¶
The following examples use public DataWay by default. When using local environment deployment, replace the reporting parameters according to Prepare Reporting Configuration.
Choose an integration entry from the table below based on your application type. NPM and CDN determine how the SDK is loaded on the page; public DataWay and local DataKit determine where data is reported. Configure them separately.
| Application Type | Recommended Entry | Description |
|---|---|---|
| Using build tools such as Webpack, Vite, or Rollup | NPM Integration | Recommended method; facilitates version management and on-demand integration, but may miss requests and errors before initialization |
| No frontend build process | CDN Asynchronous Loading | Does not block page parsing, but may miss requests and errors before initialization |
| Need to collect page errors and requests as early as possible | CDN Synchronous Loading | Initializes as early as possible, but consumes page load time |
| Need only basic RUM and care about frontend bundle size | Slim RUM SDK | Retains regular RUM collection; does not include Session Replay or reporting compression |
| React, Vue, and Angular single-page applications | Frontend Framework Plugin Integration | Automatically manages Router View and framework errors |
| Next.js and Nuxt | Integration with SSR Frameworks | Distinguishes server-side and browser environments to avoid duplicate Views |
| Electron | Electron Application Integration | Initialize only in the renderer process |
| WebView pages in an App | WebView Page Integration | Distinguishes regular integration from App-embedded-only scenarios; configure the Bridge on the host side for each platform |
NPM Integration¶
Install and import the SDK in the frontend project:
Initialize the SDK in the project:
import { datafluxRum } from "@cloudcare/browser-rum"
datafluxRum.init({
applicationId: "<APPLICATION_ID>",
site: "<PUBLIC_DATAWAY_URL>",
clientToken: "<CLIENT_TOKEN>",
service: "web-app",
env: "production",
version: "1.0.0",
sessionSampleRate: 100,
trackUserInteractions: true
})
CDN Synchronous Loading¶
Add the script to the HTML file:
<script
src="https://static.guance.com/browser-sdk/v3/dataflux-rum.js"
type="text/javascript"
></script>
<script>
window.DATAFLUX_RUM &&
window.DATAFLUX_RUM.init({
applicationId: "<APPLICATION_ID>",
site: "<PUBLIC_DATAWAY_URL>",
clientToken: "<CLIENT_TOKEN>",
service: "web-app",
env: "production",
version: "1.0.0",
sessionSampleRate: 100,
trackUserInteractions: true
})
</script>
CDN Asynchronous Loading¶
Add the script to the HTML file:
<script>
;(function (h, o, u, n, d) {
h = h[d] = h[d] || {
q: [],
onReady: function (c) {
h.q.push(c)
},
}
d = o.createElement(u)
d.async = 1
d.src = n
n = o.getElementsByTagName(u)[0]
n.parentNode.insertBefore(d, n)
})(
window,
document,
"script",
"https://static.guance.com/browser-sdk/v3/dataflux-rum.js",
"DATAFLUX_RUM"
)
DATAFLUX_RUM.onReady(function () {
DATAFLUX_RUM.init({
applicationId: "<APPLICATION_ID>",
site: "<PUBLIC_DATAWAY_URL>",
clientToken: "<CLIENT_TOKEN>",
service: "web-app",
env: "production",
version: "1.0.0",
sessionSampleRate: 100,
trackUserInteractions: true
})
})
</script>
DOM-only Session Replay¶
Starting from Browser SDK 3.3.25, when a page needs RUM events and DOM replay, you can load the DOM replay script.
If you need to record Canvas 2D or WebGL, use the full RUM script. Load only one entry per page. The initialization and replay sampling configurations are the same as those for the full version.
Slim RUM SDK¶
A slim version is available starting from RUM SDK 3.3.3. The slim version uses the same initialization method as the full version and supports regular RUM capabilities such as View, Resource, Long Task, Error, Action, user and global Context, custom events, and distributed tracing. It is suitable for applications that do not need page recording and want to reduce the frontend bundle size.
NPM Integration¶
Replace the regular RUM package with the slim package of the same version:
import { datafluxRum } from "@cloudcare/browser-rum-slim"
datafluxRum.init({
applicationId: "<APPLICATION_ID>",
site: "<PUBLIC_DATAWAY_URL>",
clientToken: "<CLIENT_TOKEN>",
service: "web-app",
env: "production",
version: "1.0.0",
sessionSampleRate: 100,
trackUserInteractions: true
})
CDN Integration¶
The synchronous or asynchronous loading method is the same as that for the full version; only replace the script file name with the corresponding file for the slim version. The following is a synchronous loading example:
<script
src="https://static.guance.com/browser-sdk/v3/dataflux-rum-slim.js"
type="text/javascript"
></script>
<script>
window.DATAFLUX_RUM &&
window.DATAFLUX_RUM.init({
applicationId: "<APPLICATION_ID>",
site: "<PUBLIC_DATAWAY_URL>",
clientToken: "<CLIENT_TOKEN>",
service: "web-app",
env: "production",
version: "1.0.0",
sessionSampleRate: 100,
trackUserInteractions: true
})
</script>
Feature Differences from the Full Version¶
The slim version does not include the following capabilities:
- Session Replay, as well as recording APIs such as
startSessionReplayRecording(),stopSessionReplayRecording(), andisRecording(); - Canvas 2D and WebGL/WebGL2 recording, as well as Canvas APIs such as
snapshotCanvas(); compressIntakeRequestsreporting compression and the corresponding Worker.
The slim version forces sessionReplaySampleRate, sessionReplayOnErrorSampleRate, and replayCanvasEnabled to be disabled, and forces compressIntakeRequests to false. Do not pass these configurations during integration, and you do not need to set workerUrl or replayCanvasWorkerUrl. If you later need Session Replay, Canvas recording, or compressed reporting, switch the NPM package or CDN file back to the full version. Other basic initialization parameters can continue to be used.
Verify Integration¶
The following steps are for independent reporting by the Web SDK; for App WebView Bridge mode, see WebView Data Verification directly.
- Open a page integrated with the SDK, and perform a page navigation, button click, and API request.
- In the Network panel of the browser developer tools, filter for
/v1/write/rumand confirm that a successful reporting request exists. - Check the Console and confirm that there are no initialization errors such as
Application ID is not configuredordatakitOrigin or site is not configured. - Go to RUM > Application List, open the corresponding Web application, and filter in the Explorer by
service,env, andversionfrom the integration configuration to confirm that View, Resource, or Action data has been received.
Seeing View data means basic integration is successful
Error, Resource, and Action appear only after the corresponding events actually occur on the page. If there is no data, first check whether the current Session matches sessionSampleRate, then refer to the FAQ.
Get SDK Initialization Result¶
Both the Web RUM full version and slim version support initialization callbacks starting from Browser SDK 3.3.25.
Configure onInitSuccess and onInitError in the existing init() call. When using CDN asynchronous loading, call init() inside onReady().
After the SDK completes configuration validation and necessary session storage checks, it calls onInitSuccess. If remote configuration (remoteConfiguration) is enabled, the SDK processes remote configuration first. When compressed reporting is enabled in the full version, the success callback also waits for the compression Worker to be ready. Automatically collected Views may be generated before the callback. The slim version and the full version using JSON reporting do not need to wait for the compression Worker.
The following example uses public DataWay. Pass initOptions to the current RUM instance's init(initOptions).
const initOptions = {
applicationId: "<APPLICATION_ID>",
site: "<PUBLIC_DATAWAY_URL>",
clientToken: "<CLIENT_TOKEN>",
remoteConfiguration: true,
onInitSuccess(result) {
console.log("RUM 初始化成功", result.remoteConfiguration)
if (result.remoteConfiguration === "fallback") {
console.warn("RUM 已使用本地配置启动", result.remoteConfigurationError.code)
}
},
onInitError(error) {
console.error("RUM 初始化失败", error.code, error.message)
}
}
result.remoteConfiguration |
Meaning |
|---|---|
disabled |
Remote configuration is disabled, and the SDK completes initialization using local configuration. |
applied |
The SDK has processed a valid remote response. When an empty configuration is returned, the local configuration still takes effect. |
fallback |
The remote request or response parsing failed, and the SDK completes initialization using local configuration. remoteConfigurationError contains code and message; HTTP errors also contain status. |
The remote request timeout is 10 seconds. Timeouts, network errors, non-200 responses, or response format errors all trigger fallback to local configuration. If the local configuration also cannot start the SDK, this call only triggers onInitError.
Each init() call triggers at most one result callback. init() returns undefined, and the callback may execute synchronously before it returns. If you manage views manually, you can call startView() in onInitSuccess to create the first view. For independent reporting by the Web SDK, follow Verify Integration to check browser requests and view View data in the corresponding Web application. When App WebView Bridge is enabled, data is reported by the App SDK; follow WebView Data Verification to view View data in the corresponding App application.
error.code |
Handling |
|---|---|
invalid_configuration, invalid_plugins |
Check the parameters and plugin settings after local or remote overrides, correct them, and call init() again. |
storage_unavailable |
Check the browser cookie, localStorage, and session storage configurations, restore storage, and try again. |
worker_initialization_failed |
The compression Worker in the full version failed to start or timed out. The SDK notifies once through onInitError. Check error.message, and follow the prompt to check the Worker address (workerUrl), network connection, or Content Security Policy (CSP). After correction, refresh the page to reinitialize. Subsequent calls to init() on the current page are ignored. |
already_initialized |
This call is rejected, and the first call retains its callback. silentMultipleInit only controls console prompts. |
initialization_ignored |
The current instance delegates initialization to the instance injected by Synthetics. |
sdk_disabled, initialization_failed |
An exception occurred during SDK construction or startup. Investigate and fix the cause, then refresh the page. |
Common Optional Configurations¶
After basic data is confirmed successfully, enable other capabilities as needed:
| Goal | Configuration or API | Documentation |
|---|---|---|
| Correlate frontend and backend traces | allowedTracingUrls, traceType |
Distributed Tracing Configuration |
| Limit API request frequency by anonymous visitor | visitorId, resetVisitorId() |
Visitor ID |
| Control collection ratio | sessionSampleRate, startSession() |
Sampling Configuration |
| Collect only error session events | sessionOnErrorSampleRate |
Error Session Compensation Sampling |
| Enable Session Replay | startSessionReplayRecording() |
Web Session Replay |
| Compress reported data | compressIntakeRequests |
Data Compression |
| Automatically manage SPA Router View | plugins |
Frontend Framework Plugin Integration |
| Record WebGL/WebGL2 | plugins, automatic Canvas recording |
Canvas Recording Guide |
| Identify logged-in users | setUser() |
Custom User Identification |
| Add business fields or events | Global Context, addAction(), addError() |
Custom Data and Events |
Distributed Tracing Configuration (Optional)¶
When integrating with NPM + TypeScript, traceType must use the TraceType enum imported from the corresponding brand's browser-core package:
import { TraceType } from "@cloudcare/browser-core"
import { datafluxRum } from "@cloudcare/browser-rum"
datafluxRum.init({
applicationId: "<APPLICATION_ID>",
site: "<PUBLIC_DATAWAY_URL>",
clientToken: "<CLIENT_TOKEN>",
allowedTracingUrls: ["https://api.example.com"],
traceType: TraceType.DDTRACE
})
The runtime value of TraceType.DDTRACE is still "ddtrace". CDN integration does not use module imports; when configuring explicitly, use the corresponding runtime string. After enabling distributed tracing, you also need to allow the corresponding Trace Header on the API server. For details, refer to How APM Connects to RUM.
If a regular Session does not match sampling but you still need to pass the Trace Header to the backend, you can explicitly enable allowTraceHeaderWithoutSession:
datafluxRum.init({
applicationId: "<APPLICATION_ID>",
site: "<PUBLIC_DATAWAY_URL>",
clientToken: "<CLIENT_TOKEN>",
sessionSampleRate: 0,
sessionOnErrorSampleRate: 0,
allowedTracingUrls: ["https://api.example.com"],
allowTraceHeaderWithoutSession: true
})
After enabling it, the SDK still injects the Trace Header only into XHR and Fetch requests that match allowedTracingUrls. This configuration does not create or force-enable a RUM Session, nor does it report View, Error, Resource, or Action data for unsampled Sessions. The API service still needs to allow the request header corresponding to the selected traceType; cross-origin requests also require correct CORS configuration.
Parameter Configuration¶
Initialization Parameters¶
| Parameter | Type |
Required |
Default |
Description |
|---|---|---|---|---|
applicationId |
String | Yes | Application ID created from Guance. | |
datakitOrigin |
String | For local environment deployment | DataKit data reporting address, in the format protocol (including ://) + domain or IP + optional port, for example https://datakit.example.com. |
|
clientToken |
String | For public DataWay | Public DataWay data reporting Token, obtained from the Guance console. | |
site |
String | For public DataWay | Public DataWay data reporting address, obtained from the Guance console. | |
env |
String | No | Current environment of the Web application, such as prod: production environment; gray: canary environment; pre: staging environment; common: daily environment; local: local environment. | |
version |
String | No | Version number of the Web application. | |
service |
String | No | Service name of the current application. The default is browser, and custom configuration is supported. |
|
sessionSampleRate |
Number | No | 100 |
Percentage of metric data collection: 100 means collect all; 0 means collect none. |
sessionOnErrorSampleRate |
Number | No | 0 |
Error session compensation sampling rate: when a session is not sampled by sessionSampleRate, if an error occurs during the session, collect the session at this rate. Such sessions start recording events when the error occurs and continue recording until the session ends. SDK version requirement: >= 3.2.19 |
sessionReplaySampleRate |
Number | No | 100 |
Session Replay data collection percentage: 100 means collect all; 0 means collect none. |
sessionReplayOnErrorSampleRate |
Number | No | 0 |
Session Replay error session replay compensation sampling rate: when a session is not sampled by sessionReplaySampleRate, if an error occurs during the session, collect the session at this rate. Such replays record up to one minute of events before the error occurs and continue recording until the session ends. SDK version requirement: >= 3.2.19 |
trackSessionAcrossSubdomains |
Boolean | No | false |
Share cache across subdomains under the same domain. |
usePartitionedCrossSiteSessionCookie |
Boolean | No | false |
Whether to enable partitioned secure cross-site session cookies Details |
useSecureSessionCookie |
Boolean | No | false |
Use secure session cookies. This disables RUM events sent over insecure (non-HTTPS) connections. |
traceType |
TraceType |
No | TraceType.DDTRACE (runtime value is ddtrace) |
Configure the distributed tracing tool type. NPM integration uses the TraceType enum, and CDN integration uses the corresponding runtime string. Currently supports DDTRACE (ddtrace), ZIPKIN_MULTI_HEADER (zipkin), ZIPKIN_SINGLE_HEADER (zipkin_single_header), W3C_TRACEPARENT (w3c_traceparent), W3C_TRACEPARENT_64 (w3c_traceparent_64bit), SKYWALKING_V3 (skywalking_v3), and JAEGER (jaeger).❗️ 1. OpenTelemetry supports four types: zipkin_single_header, w3c_traceparent, zipkin, and jaeger.2. The effectiveness of this configuration depends on allowedTracingUrls.3. When configuring the corresponding type, you need to set the corresponding Access-Control-Allow-Headers for the API service. For details, refer to How APM Connects to RUM. |
traceId128Bit |
Boolean | No | false |
Whether to generate traceID in 128-bit mode. This corresponds to traceType and currently supports zipkin and jaeger. |
allowedTracingUrls |
Array | No | [] |
List of request URL matches allowed to inject the Trace Header. Array items can be a full URL, a regular expression, a match function, or an object containing match and traceType. For example: ["https://api.example.com/xxx", /https:\/\/.*\.my-api-domain\.com\/xxx/, (url) => url.includes("/api/")]. |
allowTraceHeaderWithoutSession |
Boolean | No | false |
Whether to still inject the Trace Header into XHR and Fetch requests that match allowedTracingUrls when the current RUM Session is not sampled. Enabling this does not create a Session and does not report RUM data for unsampled Sessions. |
allowedTracingOrigins |
Array | No | [] |
Deprecated and retained only for compatibility with older configurations. For new integrations, use allowedTracingUrls; when both are configured, allowedTracingUrls overrides this configuration. |
trackUserInteractions |
Boolean | No | false |
Whether to enable user interaction collection. |
enablePrivacyForActionName |
Boolean | No | false |
Whether automatic Action names follow the DOM privacy level. When enabled, masked names use fixed placeholders, and clicks in hidden elements do not generate automatic Actions; explicitly configured Action name attributes remain available. SDK version requirement: >= 3.3.14. See Protect Automatic Action Names for details. |
trackViewsManually |
Boolean | No | false |
Whether to disable automatic SDK Views and have the application call startView() to start Views manually. Framework Router plugins automatically manage this configuration, so the business does not need to set it again. Details |
plugins |
Array | No | [] |
Register RUM plugins and pass them during init(). Framework plugins can collect route Views and framework errors for React, Vue, Angular, Next.js, and Nuxt. SDK version requirement: >= 3.3.6. For details, refer to Frontend Framework Plugin Integration. WebGL Replay is available starting from SDK 3.3.7, requires RUM main package version >= 3.3.7, and it is recommended that the plugin and main package use the same SDK release version. For details, refer to Canvas Recording Guide. |
enableExperimentalFeatures |
Array | No | [] |
Enable experimental features. Configure ["track_websockets"] to collect native WebSocket connection-level Resources. SDK version requirement: >= 3.3.6. Details |
actionNameAttribute |
String | No | Version requirement: >3.1.2. Add a custom attribute to an element to specify the action name. For specific usage, see details. |
|
beforeSend |
Function(event, context):Boolean | No | Version requirement: >3.1.2. Data interception and data modification. Details |
|
storeContextsToLocal |
Boolean | No | Version requirement: >3.1.2. Whether to cache user-defined data in local localStorage, such as custom data added by the setUser and addGlobalContext APIs. |
|
storeContextsKey |
String | No | Version requirement: >3.1.18. Define the key stored in localStorage. Leave it blank by default to generate automatically. This parameter mainly distinguishes the store sharing problem across different subpaths under the same domain. For configurations of user identification and session boundaries, see Page Refresh and Local Storage. |
|
compressIntakeRequests |
Boolean | No | Compress RUM data request content to reduce bandwidth usage when sending large amounts of data and reduce the number of data request sends. Compression is performed in a Web Worker thread. For CSP security policies, see CSP security. SDK version requirement: >= 3.2.0. DataKit version requirement: >=1.60. Deployment Plan requirement: >= 1.96.178. |
|
workerUrl |
String | No | Both sessionReplay and compressIntakeRequests data compression are performed in a Web Worker thread. Therefore, by default, when CSP security access is enabled, you need to allow worker-src blob:;. This configuration allows adding a self-hosted Worker address. For CSP security policies, see CSP security. SDK version requirement: >= 3.2.0. |
|
remoteConfiguration |
Boolean | No | Whether to enable the remote configuration feature for data collection. It is disabled by default. Remote configuration can dynamically modify data collection configuration items without releasing a new version. For example, you can modify the sampling rate and whether to enable user interaction collection in the remote configuration. The remote configuration feature requires enabling environment variable settings in the Guance console. SDK version requirement: >= 3.2.20. DataKit version requirement: >=1.60. How to Enable Environment Variables in the Guance Console |
|
onInitSuccess |
function |
No | Supported in SDK 3.3.25 and later. Called when initialization succeeds. The parameter contains the remote configuration processing result. See Initialization Result for details. |
|
onInitError |
function |
No | Supported in SDK 3.3.25 and later. Triggered when this initialization fails or the call is rejected. The parameter contains code and message. See Error Codes for details. |
|
replayCanvasWorkerUrl |
string |
No | Dedicated Worker address for canvas snapshot encoding. It does not replace workerUrl. This configuration allows adding a self-hosted Worker address. For CSP security policies, see CSP security. SDK version requirement: >= 3.3.0. |
|
replayCanvasEnabled |
boolean |
No | false |
Whether to enable canvas recording. If not enabled, canvas is not collected. SDK version requirement: >= 3.3.0. |
replayCanvasMode |
'manual' \| 'auto' |
No | auto |
Canvas recording mode. manual requires manually calling snapshotCanvas(canvas); auto is automatic recording. |
replayCanvasSampling |
number \| 'all' |
No | 2 |
Takes effect only when replayCanvasMode: 'auto'. A positive number selects the automatic snapshot path; it is recommended to start from 2. The value itself does not control the collection frequency of Canvas 2D. 'all' makes Canvas 2D attempt higher-fidelity command capture; complex scenarios may still fall back to snapshots. The WebGL plugin always uses budgeted pixel snapshots. |
replayCanvasAutoInterval |
number |
No | 250 |
Target interval for automatic snapshots of each Canvas, in milliseconds. Multiple Canvases are rotated fairly, and the actual cadence is also limited by cooldown, backoff, page visibility, and the global runtime budget. |
replayCanvasQuality |
'low' \| 'medium' \| 'high' \| number |
No | 0.4 |
Canvas snapshot encoding quality. String presets also adjust the sampling and automatic scheduling budget; if you only want to change image quality, pass a number between 0 and 1. |
replayCanvasAutoCooldown |
number |
No | 250 |
Minimum cooldown time between automatic snapshots of the same Canvas, in milliseconds. |
replayCanvasAutoUnchangedBackoff |
number |
No | 3000 |
Interval before the next full encoding verification when the lightweight signature remains unchanged, in milliseconds; during this period, changes are still detected at a bounded, adaptive cadence. |
replayCanvasAutoFailureBackoff |
number |
No | 5000 |
Backoff time after automatic collection fails, in milliseconds. |
replayCanvasAutoMaxPerRun |
number |
No | 2 |
Maximum number of Canvases processed in a single automatic scheduling run. |
replayCanvasFlushImmediately |
boolean |
No | manual: trueauto: false |
Whether to prioritize flush after a Canvas frame successfully enters replay. |
silentMultipleInit |
boolean |
No | Whether to disable console prompts for duplicate initialization. A configured onInitError still receives already_initialized. |
When the low, medium, and high string presets are not used, the Canvas automatic scheduling baseline is: sampling 2, target interval 250 ms per Canvas, cooldown 250 ms, unchanged backoff 3000 ms, failure backoff 5000 ms, and a maximum of 2 Canvases per run. String presets replace these budgets and encoding quality at the same time; multiple Canvases are also subject to fair rotation and the global collection budget. Explicit individual configurations override the corresponding values in the preset. For the complete preset matrix, see the Canvas Recording Guide.
The high-frequency scheduling baseline above is for Canvas 2D. When interval/cooldown is not explicitly configured, the WebGL plugin continues to use a more conservative GPU readback cadence; only explicit individual configurations override them separately.
Public DataWay Site Addresses¶
site specifies the public data receiving address. Prefer copying the address from the current application's integration configuration. The table below is for verifying sites; when using local environment deployment, configure datakitOrigin only.
| Node Name | Address |
|---|---|
| China Zone 1 (Hangzhou) | https://rum-openway.guance.com |
| China Zone 2 (Ningxia) | https://aws-openway.guance.com |
| China Zone 4 (Guangzhou) | https://cn4-openway.guance.com |
| China Zone 6 (Hong Kong) | https://cn6-openway.guance.one |
| International Zone 1 (Oregon) | https://us1-openway.guance.com |
| Europe Zone 1 (Frankfurt) | https://eu1-openway.guance.one |
| Asia Pacific Zone 1 (Singapore) | https://ap1-openway.guance.one |
| Asia Pacific Zone 2 (Singapore) | https://ap2-openway.guance.com |
| Africa Zone 1 (South Africa) | https://za1-openway.guance.com |
| Indonesia Zone 1 (Jakarta) | https://id1-openway.guance.com |
Runtime Session Control¶
RUM SDK 3.3.6 adds startSession(). After it is called, the current Session ends immediately and a new Session starts according to the current sampling configuration, without waiting for the next user interaction:
You can also override the runtime sessionSampleRate at the same time:
The sampling rate must be between 0 and 100. The override applies to this Session and subsequent automatically renewed Sessions. Both the full RUM package and the slim RUM package support this API. For detailed semantics and Use Cases, see Restart Session at Runtime.
Enable Advanced Capabilities as Needed¶
Collect Only Error Session Events¶
Version Requirement
SDK version requirement: >= 3.2.19.
sessionOnErrorSampleRate compensates for error sessions that do not match regular sampling. When an error occurs in a session and the session matches compensation sampling, the SDK starts recording events when the error occurs and continues until the session ends.
The following example disables regular session sampling and sets the error session compensation sampling rate to 100%.
Configuration Plan¶
window.DATAFLUX_RUM &&
window.DATAFLUX_RUM.init({
applicationId: "<APPLICATION_ID>",
site: "<PUBLIC_DATAWAY_URL>",
clientToken: "<CLIENT_TOKEN>",
sessionSampleRate: 0,
sessionOnErrorSampleRate: 100
})
The above example uses public DataWay. For local environment deployment, replace the reporting address fields according to the basic integration example.
Data Compression¶
When a page contains many static resources (such as JS, CSS, and images) or the sampling rate is high, a large amount of RUM reporting data may be generated.
After setting compressIntakeRequests: true, the SDK uses deflate in a Web Worker to compress reported data, reducing request size and the number of requests.
Configuration Example¶
window.DATAFLUX_RUM &&
window.DATAFLUX_RUM.init({
applicationId: "<APPLICATION_ID>",
site: "<PUBLIC_DATAWAY_URL>",
clientToken: "<CLIENT_TOKEN>",
compressIntakeRequests: true
})
Notes¶
- The data compression logic runs in a Web Worker. If a CSP security policy is enabled, you need to allow
blob:inworker-src. For more information, see CSP Security Policy Description. - The SDK supports specifying a self-hosted Worker address through the
workerUrlconfiguration item. - The SDK version using this feature must be >= 3.2.
Custom Data and Events¶
Choose the corresponding API based on your business goal, and view CDN and NPM integration examples and parameter descriptions:
- Track User Actions: automatically collect clicks, define Action names, and add custom Actions.
- Custom User Identification: set the user after login, and clear the user when logging out or switching accounts.
- Global Context: add stable business dimensions to all subsequent RUM events.
- Add Custom Actions: record business operations that cannot be expressed through page clicks.
- Report Custom Errors: report exceptions that have been captured or actively identified by the business.
Web Session Replay¶
Prerequisite
Use the full RUM package that includes Session Replay; the slim RUM package does not include Session Replay capabilities.
Enable Recording¶
After SDK initialization, call the startSessionReplayRecording() method to enable Session Replay recording. You can choose to enable it under specific conditions, such as enabling session recording after a user logs in.
Collect Only Error-related Session Replay Data¶
Version Requirement
SDK version requirement: >= 3.2.19.
sessionReplayOnErrorSampleRate compensates for error sessions that do not match regular replay sampling. When an error occurs in a session and the session matches compensation sampling, replay data from up to 1 minute before the error can be captured, and recording continues until the session ends.
The following example collects all RUM sessions, disables regular replay sampling, sets the error session replay compensation sampling rate to 100%, and calls the recording API. Session Replay is still subject to RUM session sampling results. For specific rules, see Sampling Configuration.
Configuration Example¶
window.DATAFLUX_RUM &&
window.DATAFLUX_RUM.init({
applicationId: "<APPLICATION_ID>",
site: "<PUBLIC_DATAWAY_URL>",
clientToken: "<CLIENT_TOKEN>",
sessionSampleRate: 100,
sessionReplaySampleRate: 0,
sessionReplayOnErrorSampleRate: 100
})
window.DATAFLUX_RUM && window.DATAFLUX_RUM.startSessionReplayRecording()
Notes¶
- Session Replay does not record the playback content of iframes, videos, or audio; Canvas is not collected by default and requires separate configuration of
replayCanvasEnabled. WebGL/WebGL2 is available starting from SDK3.3.7, requires RUM main package version>= 3.3.7, and also requires additionally installing and registering a compatiblebrowser-rum-webglplugin. It is recommended that the plugin and main package use the same SDK release version. For details, see the Canvas Recording Guide; - To ensure that static resources (such as fonts and images) can be accessed normally during replay, you may need to configure a CORS policy;
- Ensure that CSS rules are accessible through the CSSStyleSheet interface to support CSS styles and mouse hover events.
Verify Recording Status¶
Call window.DATAFLUX_RUM.isRecording() to check whether the current page is being recorded, and confirm in the Session Replay Explorer that the corresponding Session has generated replay data. In production, adjust sessionReplaySampleRate according to business requirements.