Web SDK

Updated at:

SDK integration

Step

Task

Reference

Requirement

Notes

Step 1

SDK acquisition

See "Step 1: SDK Integration".

Required

Use NPM or CDN, based on your environment.

Step 2

Set initialization parameters

See "Step 2: Set initialization parameters - Set the appkey".

Required

Set initialization parameters

See "Step 2: Set initialization parameters - Set the data reporting endpoint".

Required

Set initialization parameters

See "Step 2: Set initialization parameters - Configure denylist/allowlist with pageFilter".

Optional

Use pageFilter to filter logs.

Set initialization parameters

See "Step 2: Set initialization parameters - Set the log level".

Optional

Appendix

Compatibility

See "Appendix: Compatibility".

Note: Before starting the web integration, you must obtain an appkey.

SDK integration

The web SDK supports two integration methods: CDN and npm.

Note:

  1. CDN URL:APM H5 SDK

  2. Npm command: npm install lydaas_apm --save

  3. For private network environments, upload the SDK JavaScript file to your static resource server. Then, replace the CDN URL in the integration code with the file's URL.

  4. Initialization starts data collection.

CDN

Synchronous vs. asynchronous loading

Asynchronous loading, also known as non-blocking loading, lets the browser continue rendering the page while downloading and executing JS. Use this method when page performance is a high priority.(Asynchronous loading cannot capture JS errors or resource loading errors that occur before the SDK is fully loaded and initialized.)

Synchronous loading, also known as blocking loading, defers subsequent processing until the current JS file finishes loading. This method is recommended for capturing JS errors and resource loading errors that occur throughout the page lifecycle.

Asynchronous loading

Scenario 1: Asynchronous CDN initialization

<script>
  void (function (e, t, n, a, o, i, m) {
    (e._um_apm_namespace = o),
    (e[o] = e[o] || function () {
          (e[o].q = e[o].q || []).push(arguments);
    }),
    (e[o].l = e[o].l || +new Date()),
    (i = t.createElement(n)),
    i.setAttribute('crossorigin', ''),
    (i.src = a),
    (m = t.getElementsByTagName(n)[0]),
    m.parentNode.insertBefore(i, m);
  })(
    window,
    document,
    'script',
    'https://g.alicdn.com/QTSDK/oxm-web-apm/2.1.5/es5/uapm.umd.js',
    '_apm',
  );
  _apm('create', {
    pid: 'YOUR_APPLICATION_ID',
    // The DSN must start with "https://".
    dsn: 'YOUR_DSN',
    pageFilter: { mode: 'ignore', rules: [] },
    // See Step 2 for more configuration options.
  });
</script>

Scenario 2: Set initialization parameters before you import the SDK

<script>
  window._apm = window._apm || {
    p:[[
      'create', {
       pid: 'YOUR_APPLICATION_ID',
       // The DSN must start with "https://".
       dsn: 'YOUR_DSN',
       pageFilter: {
         mode: 'ignore',
         rules: [],
       },
       // For additional configuration parameters, see Step 2.
    }]],
  };
</script>

<script>
  void (function (e, t, n, a, o, i, m) {
    (e._um_apm_namespace = o),
    (e[o] = e[o] || function () {
      (e[o].q = e[o].q || []).push(arguments);
    }),
    (e[o].l = e[o].l || +new Date()),
    (i = t.createElement(n)),
     i.setAttribute('crossorigin', ''),
    (i.src = a),
    (m = t.getElementsByTagName(n)[0]),
     m.parentNode.insertBefore(i, m);
  })(
    window,
    document,
    'script',
    'https://g.alicdn.com/QTSDK/oxm-web-apm/2.1.5/es5/uapm.umd.js',
    '_apm',
  );
</script>

Synchronous loading

<script>
  window._um_apm_namespace = '_apm';
  window[_um_apm_namespace] = window[_um_apm_namespace] || {
    p: [],
  };
  window[_um_apm_namespace].p.push([
    'create',
    {
      // The dsn must start with "https://".
      dsn: 'YOUR_DSN',
      pid: 'YOUR_APPLICATION_ID',
      pageFilter: {
        mode: 'ignore',
        rules: [],
      },
      // See Step 2 for a full list of configuration parameters.
    },
  ]);
</script>

<script src="https://g.alicdn.com/QTSDK/oxm-web-apm/2.1.5/es5/uapm.umd.js" crossorigin></script>

Integrate with npm

Example: Initialization call

Prefix the domain name with "https://".

import { init } from 'lydaas_apm';

init({
  pid: 'YOUR_APPLICATION_ID',
  // Note: The domain name must be prefixed with "https://".
  dsn: 'YOUR_DATA_COLLECTION_DOMAIN',
  pageFilter: {
    mode: 'ignore',
    rules: []
  },
  errorFilter: {
    mode: 'ignore',
    rules: []
  },
  puid: "user@example.com", // The application's user account.
  tag: "", // Custom tag.
  logLevel: 0, // The log level: 0 for error, 1 for warn, 2 for info, and 3 for debug.
  enableBlankScreen: true, // Enables blank screen statistics.
  blankConfig: {
    blank_target: 'body', // The root DOM node for blank screen detection.
    blank_timeout: 6000, // Wait duration in milliseconds (ms) for pixels to render in the target DOM node.
    screenshot: true, // Send a screenshot when a blank screen is detected.
    X: 1.5, // Sends a screenshot if the DOM score is less than this value.
    Y: 6, // Sends a blank screen log if the DOM score is less than this value.
  }
});

Initialization parameters

SDK initialization parameters

Parameter

Description

Type

Default

sample

The global sampling rate (percentage).

number

undefined

logLevel

The log level.

Enum

0: ERROR

1: WARN

2: INFO

3: DEBUG

0

pid

The unique identifier for the application (appkey).

string

undefined

uid

The unique user ID.

string

undefined

puid

A custom user ID.

string

undefined

tag

Identifier for the product line. Used to distinguish different product lines under the same appkey to simplify troubleshooting.

string

undefined

environment

Identifier for the deployment environment (e.g., prodtest).

string

undefined

release

The release version of the web application.

string

undefined

dsn

The data ingestion endpoint for the SDK.

string

undefined

pkgList

An allowlist of bundle IDs for applications that send logs via the native bridge. Separate multiple bundle IDs with a comma.

'com.umeng.com,com.apm.com'

['com.umeng.com','com.apm.com']

string or Array<string>

An empty string ('') means the list is empty, and no logs are sent by default.

pageFilter

Configures an allowlist or denylist to filter data collection from H5 pages. In allowlist mode, data is collected only from matching pages. In denylist mode, data from matching pages is excluded.

This parameter filters logs based on the page URL.

object

mode: 'ignore'. When set to ignore, the filter acts as a denylist, and logs from pages matching the rules are not reported. When set to match, it acts as an allowlist, and only logs from pages matching the rules are reported.

rules: []. The default is an empty array, which acts as an empty denylist, meaning all pages are reported.

errorFilter

Configures an allowlist or denylist for H5 page error collection. You can choose from two modes:

  • Allowlist mode: Only errors from pages matching the rules are collected.

  • Denylist mode: Errors from pages matching the rules are excluded from collection.

object

mode: 'ignore'. When set to ignore, the filter acts as a denylist, and errors matching the rules are not reported. When set to match, it acts as an allowlist, and only errors matching the rules are reported.

rules: []. The default is an empty array, which acts as an empty denylist, meaning all errors are reported.

apiFilter

Configures an allowlist or denylist to filter API request logs (from XHR and fetch) based on the request URL.

object

mode: 'ignore'. When set to ignore, the filter acts as a denylist, and requests matching the rules are not reported. When set to match, it acts as an allowlist, and only requests matching the rules are reported.

rules: []. The default is an empty array, which acts as an empty denylist, meaning all requests are reported.

hookFetch

Whether to intercept fetch requests.

boolean

true. Enabled by default.

hookXHR

Whether to intercept XMLHttpRequest requests.

boolean

true. Enabled by default.

traceKey

The field name for the end-to-end tracing ID.

string

'traceId'

enableNetWorkType

Whether to enable network type detection:

  • If set to true, the SDK reports the user's network type (e.g., Wi-Fi, 4G, 3G).

  • If set to false, network type detection is disabled.

boolean

true. Enabled by default.

enableCatchJSError

Whether to automatically capture JavaScript runtime errors.

  • If set to true, the SDK automatically captures the following errors:

    • Uncaught JavaScript exceptions (via window.onerror or addEventListener('error'))

    • Unhandled promise rejections (via window.onunhandledrejection)

    • Other runtime errors (such as syntax errors or resource loading failures), depending on the SDK implementation

  • If set to false, the automatic error capturing feature is disabled.

boolean

true. Enabled by default.

enablePerformance

Whether to collect page performance metrics.

boolean

true. Enabled by default.

enableJSBridge

Whether to enable the JavaScript bridge.

boolean

true. Enabled by default.

enableFID

Whether to calculate the first input delay (FID).

boolean

true. Enabled by default.

enableRemoteConfig

Whether to enable remote configuration.

boolean

true. Enabled by default.

enableBlankScreen

Whether to enable blank screen detection.

boolean

true. Enabled by default.

sampleConfig

Sampling configuration.

object

{

enable: true, sampleRate: 50, rules: {

perf: {

enable: false // Disable performance sampling

}

}

}

blackConfig

Blank screen configuration.

object

{

blank_target:'body', // The target element for blank screen detection.

blank_timeout:6000, // Delay (in ms) after page load before checking for a blank screen.

screenshot:true, // Whether to send a screenshot.

X:1.5, // Screenshot threshold. The SDK sends a screenshot if the DOM score is below this value.

Y:6, // Blank screen log threshold. The SDK sends a log if the DOM score is below this value.

}

xhrConfig

Configuration for XHR requests.

object

{

enableReqBody:true // Whether to collect the XHR request body. By default, the SDK collects the body if the response status code is greater than 400.

}

fetchConfig

Configuration for fetch requests.

object

{

enableReqBody:true // Whether to collect the fetch request body. By default, the SDK collects the body if the response status code is greater than 400.

}

enableCrypt

Whether to enable data encryption.

boolean

false. Disabled by default.

enableScreenCrypt

Whether to enable screenshot encryption.

boolean

false. Disabled by default.

data2Encrypt

The data encryption function.

Function

Returns the original input and header.

data2Decrypt

The data decryption function.

Function

Returns the original input and header.

Appkey

Required

Parameter

Description

Default

Type

pid

The unique identifier (appkey) for the client application.

-

string

User product line tag (Optional)

Parameter

Description

Default

Type

tag

The product line identifier, used to distinguish between product lines under the same appkey and simplify troubleshooting.

-

string

SDK service endpoint

Required

Parameter

Description

Default

Type

dsn

The SDK's collection service address

-

string

Configure pageFilter for allowlist and denylist

You can set the H5 page collection mode to allow list or deny list:

  • In whitelist mode, the crawler crawls only pages that match a rule.

  • In blacklist mode, the crawler does not crawl pages that match a rule.

This optional parameter filters logs by URL and contains the following attributes.

Parameter

Description

Default

Type

mode

Matching mode

The 'ignore' value enables deny list mode, which prevents log reporting for matching URLs. The 'match' value enables allow list mode, which reports logs only for matching URLs.

ignore

enum: ignore|match

rules

The matching logic for the rule set is as follows:

  • When a rule is a string, it matches if the page URL contains that string.

  • When a rule is a function, it matches if the function returns true. A return value of false indicates no match.

  • An array of rules acts as a rule set, matching if any rule within it matches (a logical OR operation).

[], which means the deny list is empty, so all logs are reported.

  • string

  • RegExp

  • function

  • array<string | RegExp | function>

Configure errorFilter for allow and deny lists (Optional)

Use this feature to configure data collection on H5 pages. You can choose between two modes:

  • In allow list mode, only pages that match the configured rules are collected.

  • In deny list mode, pages that match the configured rules are excluded from collection.

This optional parameter filters logs based on custom conditions and includes the following attributes:

Parameter

Description

Default

Type

mode

Match mode

The ignore setting enables blacklist mode, which does not report logs that match a rule. The match setting enables whitelist mode, which reports only logs that match a rule.

ignore

An enum. Possible values are ignore or match.

rules

A collection of match rules:

  • When a rule is a String, it matches if the page URL contains this string.

  • When a rule is a Function, it matches if the function returns true.

  • When a rule is an Array, it is a collection of rules. The collection matches if any of its rules match (logical OR).

[]. The default is an empty blacklist, so all logs are reported.

  • String

  • RegExp

  • Function

  • Array<String | RegExp | Function>

API filter for allowlist/denylist (optional)

Use this feature to configure an allowlist/denylist that filters xhr and fetch requests for the API log by their request URL.

Parameter

Description

Default

Type

mode

The match mode.

A value of ignore enables blocklist mode, where items that match a rule are not reported. A value of match enables allowlist mode, where only items that match a rule are reported.

ignore

Enum: ignore | match

rules

The set of match rules:

  • A string rule matches if the page URL contains the string.

  • A Function rule matches if it returns true.

  • An array of rules matches if any rule within it matches (logical OR).

[] (an empty array). With the default blocklist mode, an empty array means no rules are defined, so all logs are reported.

  • string

  • RegExp

  • Function

  • array<string | RegExp | Function>

API request parameters (Optional)

Parameter

Description

Default

Type

hookXHR

Whether to intercept XMLHttpRequest requests.

true

boolean

hookFetch

Whether to intercept fetch requests.

true

boolean

xhrConfig

Configuration for XMLHttpRequest requests.

{

enableReqBody:true

}

object

fetchConfig

Configuration for fetch requests.

{

enableReqBody:true

}

object

xhrConfig

Parameter

Description

Default

Type

enableReqBody

Whether to enable request body collection for XHR requests. By default, request bodies are collected only for responses with a status code of 400 or higher.

true

boolean

fetchConfig

Parameter

Description

Default

Type

enableReqBody

Enables collection of the fetch request body. By default, the body is only collected for responses with a status code greater than 400.

true

boolean

Log level (optional)

(Optional) Specifies the JavaScript log level.

Parameter

Description

Default

Type

logLevel

The log level.

0

enumerated value

0: ERROR

1: WARN

2: INFO

3: DEBUG

White screen detection

Optional. Configures white screen detection standards, the screenshot function, and related settings.

Parameter

Description

Default

Type

enableBlankScreen

Enables or disables the blank screen check.

true

boolean

blankConfig

Configuration for the blank screen check.

{

blank_target:'body',

blank_timeout:6000,

screenshot:true,

X:1.5,

Y:6,

}

object

blankConfig

Parameter

Description

Default

Type

blank_target

The target element for the blank screen check.

body

string

blank_timeout

The delay in milliseconds after page load before running the blank screen check.

6000

number

screenshot

Whether to send a screenshot.

true

boolean

X

The DOM score threshold below which a screenshot is sent.

1.5

number

Y

The DOM score threshold below which a blank screen log is sent.

6

number

End-to-end request injection (optional)

Optional: injects an HTTP header into the H5 application's business requests.

Note: Request logs initiated by sendAPILog do not support HTTP header injection.

Parameter

Description

Default

Type

rumConfig

Configures header injection to link Real User Monitoring (RUM) requests with backend traces.

-

object

rumConfig

Parameter

Description

Default

Type

injectTraceHeader

Specifies the trace context protocol for outgoing HTTP requests. The SDK automatically generates and injects the corresponding request header.

undefined

Enum

  • traceparent

  • b3

  • sw8

  • sentry-trace

needTracedUrls

An allowlist of URLs for end-to-end tracing header injection.

null. If set, the SDK only injects the request header into URLs that match a rule in this allowlist.

Array<string | RegExp>

ignoredUrls

A denylist of URLs to exclude from end-to-end tracing header injection.

null. If set, the SDK does not inject the request header into URLs that match a rule in this denylist.

Array<string | RegExp>

injectSDKRequest

Specifies whether to inject the request header into the SDK's own internal requests.

false. The SDK does not inject the request header into its own internal requests.

boolean

Method

1. Manual error log submission

CaptureException

To load the SDK via CDN, use the following method.
_apm && _apm('captureException', new Error('manual capture'));
For npm imports, call the method as follows.
import { captureException } from 'lydaas_apm';
try {
  throw new Error('error manually captured by the developer');
} catch (error) {
  captureException(error);
}
This example shows an implementation in main.js for a Vue project built with Vite.
import { createApp } from 'vue';
import './style.css';
import App from './App.vue';
import { init, captureException } from 'lydaas_apm';

init({
  pageFilter: {
    mode: 'ignore',
    rules: [],
  },
  pid: 'test124',
  dsn: '//aplus2-portal-lite.emas-poc.com',
  logLevel: 4,
});

const app = createApp(App);
app.config.errorHandler = (err, instance, info) => {
    // Handle the error, e.g., by reporting it to the APM service.
    captureException(err);
};
app.mount('#app');

2. Manually submit API logs

sendAPILog

(Requires version 2.0.10 or higher.)

If you are using the SDK via a CDN, call the method as follows.
// Send an API log using the application performance monitoring (apm) agent.
_apm && _apm('sendAPILog', {
    url: 'https://example.com/getUserName',
    method: 5,
    rc: 500,    // response code
    rt: 2000,       // response time
    traceid: '1234567', // trace ID
    req_body: '{a:1}',  // request body
    req_query: '&aaa=1' // request query
});
When using an npm import, call it as follows.

Parameter

Description

Required

Type

Example

url

request URL

required

string

https://u.shujupie.com/d

method

request method

1: 'GET'

2: 'POST'

3: 'PUT'

4: 'HEAD'

5: 'DELETE'

6: 'CONNECT'

7: 'OPTIONS'

8: 'TRACE'

9: 'PATCH'

required

int

2

rt

response time (ms)

required

long

3000

rc

status code

required

int

200

traceid

trace ID

optional

string

abcdef

req_query

query parameter

optional

string

string

req_body

request body (Reported only for status codes greater than 400; empty otherwise.)

optional

string

string

3. Set user ID (optional)

Asynchronous loading via CDN
<script>
  void (function (e, t, n, a, o, i, m) {
    (e._um_apm_namespace = o),
    (e[o] = e[o] || function () {
      (e[o].q = e[o].q || []).push(arguments);
    }),
    (e[o].l = e[o].l || +new Date()),
    (i = t.createElement(n)),
     i.setAttribute('crossorigin', ''),
    (i.src = a),
    (m = t.getElementsByTagName(n)[0]),
     m.parentNode.insertBefore(i, m);
  })(
    window,
    document,
    'script',
    'https://g.alicdn.com/QTSDK/oxm-web-apm/2.1.5/es5/uapm.umd.js',
    '_apm',
  );
  _apm('create', {
    pid: 'appkey',
    dsn: 'https://example.com',
    pageFilter: { mode: 'ignore', rules: [] },
  });
</script>

<script>
  // Set the PUID for the current user.
  _apm('set', 'puid', 'user account');
</script>
Loading synchronously via CDN
<script>
  window._um_apm_namespace = '_apm';
  window[_um_apm_namespace] = window[_um_apm_namespace] || {
    p: [],
  };
  window[_um_apm_namespace].p.push([
    'create',
    {
      // Note: Prefix the DSN with "https://".
      dsn: 'https://example.com',
      pid: 'appkey',
      pageFilter: {
        mode: 'ignore',
        rules: [],
      },
    },
  ]);
</script>
<script src="https://g.alicdn.com/QTSDK/oxm-web-apm/2.1.5/es5/uapm.umd.js" crossorigin></script>

<script>
  window[_um_apm_namespace].p.push(['set', 'puid', 'user account']);
</script>
Import via npm
import { setUserConfig } from 'lydaas_apm';
setUserConfig({puid:"user_account"});

Appendix: Compatibility

Browser and platform compatibility

Browser/platform

Version

Safari

9+

Chrome

49+

IE

9+

Edge

12+

Firefox

36+

Opera

43+

Safari for iOS

9.3.2+

Android Browser

Android 4.4.2+