Web SDK API
The SDK automatically obtains the connection and reporting URLs for the AppKey’s data center, including Frankfurt and Virginia. You do not need to set baseUrl, report_url, or webSocketUrl manually.
Authentication
When the developer performs initialization, he needs to pass in the necessary information. This data structure is generated by the developer server and sent back to the browser, which is used for the MTpush initialization that the developer authorizes the browser to run. Developers need to ensure that all users who can call to obtain this data are legitimate users.
Initialize Data Structure
interface MTInitInfo {
website_push_id: string;
code: number;
master_secret: string;
passwd: string;
pull: number;
regid: string;
sess: string;
tagalias: number;
uid: number;
vapid_pubkey: string;
}
type dataType = {
code: number,
content?: string | { code: number; [key: string]: unknown },
message: string,
};
interface InitType {
report_url?: string; // Report URL, used for private cloud or custom deployments
baseUrl?: string; // Server domain; when used together with report_url, the private cloud or custom deployment logic is used
userLang?: string; // Defaults to navigator.language and must be a language value supported by the browser
safari_url?: string; // Safari push test field
appkey: string; // AppKey of the application registered on the EngageLab platform, required
user_str: string; // Unique user identifier, required
swUrl?: string; // Default: "/sw" + sdkEnv.prefix
is_temporary?: "n" | "t"; // Default: "n"
debugMode?: boolean; // Default: false
webSocketUrl?: string; // If not provided, baseUrl will be used
fail?: (data: dataType | undefined) => void; // Initialization failure callback
success?: (data: dataType | undefined) => void; // Initialization success callback
webPushcallback?: def;
canGetInfo?: (d: MTInitInfo) => void;
custom?: (Callback: () => void) => void; // Callback for custom prompts; call Callback to request notification permission
maOpen?: boolean; // Whether to enable the ma-sdk module
maChannel?: string; // Channel name used by ma-sdk; default: default-channel
appName?: string; // Website name used by ma-sdk for reporting
userIdentity?: { userId?: string; anonymousId?: string }; // User identity used by ma-sdk
maCompletion?: (code: number, msg: string) => void; // ma-sdk initialization completion callback
openUrl?: string; // Redirect link when clicking a notification
encodeSwUrl?: boolean; // Whether to encode swUrl
regidSearchPath?: string; // Page path for querying Registration ID
}
- Parameter description:
openUrl: URL to open when a notification is clicked
- If no open URL is specified when sending the notification, this value is used as the redirect link;
- If this parameter is not set, it defaults to redirecting to the integration domain;
- In multi-domain integration, this parameter enables redirect to the corresponding URL;
encodeSwUrl: Whether to encode swUrl
- Use when swUrl contains special characters (e.g. @) and the server restricts access to that URL, which can cause Service Worker registration to fail; add a re-registration mechanism and encode swUrl on retry.
regidSearchPath: Page path for querying Registration ID; default is /engagelab/regid. See Registration ID Query Guide.
Only one service worker can be registered within the same scope. When successful initialization reports an error similar to "Failed to execute 'subscribe' on 'PushManager': Subscription failed - no active Service Worker," please check any conflicts with other service workers. You may need merge the service workers or resolve the scope of the service worker.
SDK initialization
Interface Description
Initialize the interface.
window.MTpushInterface.init(Object:InitType)
Parameter Description
- For details, see [InitType Description](/docs/web-push/sdk/web-sdk-api#Initialize data structure).
- Callback Object data Description:
| Parameter name | Parameter type | Parameter description |
|---|---|---|
| code | number | return code, 0 means success, other failures, see error code |
| message | string | result description |
| content | string | Object | Failure details. For initialization failures (1003), this may be an object containing the server error code; see Server initialization error codes. |
call example
const appkey = "your_appkey";
const userStr = "adminDemo";
MTpushInterface.init({
appkey: appkey,
user_str: userStr,
fail(data) {
console.log("Online push setup failed", data);
},
success(data) {
console.log("Online push setup successful", data);
},
webPushcallback(code, tip) {
console.log("Status code and message", code, tip);
},
canGetInfo(data) {
// RegId is available here, and initialization config data can also be read from data.
console.log("Obtained RegId", MTpushInterface.getRegistrationID(), data);
// MTpushInterface.setTagsAlias({ tags: ["test1", "test2"], alias: "swefgwwefwfwfwf" });
},
custom: (requestPermission) => {
// For custom prompt settings, call requestPermission during an appropriate user action to request notification permission.
document.getElementById("subscribe")?.addEventListener("click", () => {
if (Notification.permission === "default") {
requestPermission();
} else if (Notification.permission === "denied") {
console.log("Notification permission is denied and cannot be requested");
} else {
console.log("Notification permission has already been granted");
}
});
},
});
Get RegistrationID
Interface Description
Call this API to get the RegistrationID corresponding to the current account. The corresponding value is returned only after the initialization signature is successful, otherwise an empty string is returned. This method needs to be called after the canGetInfo callback is triggered.
window.MTpushInterface.getRegistrationID()
call example
var rid = window.MTpushInterface.getRegistrationID();
stop push
Call this API to disconnect the push persistent connection established with the background and stop receiving push messages.
window.MTpushInterface.mtPush.stopPush()
Push message monitoring
Interface Description
It is recommended to call the message listener before initialization.
window.MTpushInterface.onMsgReceive(fn)
Parameter Description
| Parameter name | Parameter type | Parameter description |
|---|---|---|
| fn | function | Message receiving and processing function |
call example
window.MTpushInterface.onMsgReceive(function (res) {
if(res.type===0){
// res.data.messages[]
// res.data.messages[].msg_id
// res.data.messages[].title
// res.data.messages[].content
// res.data.messages[].extras
}else{
// res.data.title
}
});
return data
| Parameter name | Parameter type | Parameter description |
|---|---|---|
| type | number | |
| data | Object | message content |
Engagelab channel message array (messages)
| Parameter name | Parameter type | Parameter description |
|---|---|---|
| msg_id | string | message ID |
| title | string | message title |
| content | string | message content |
| extras | Object | Message extra fields |
System channel message data
Support w3c interface NotificationOptions, see mdn web docs for details.
Check push service status
window.MTpushInterface.getPushAuthority()
The returned data structure is as follows:
{
mtPush: {
code:1, //1 is successful, -1 is in initialization, 0 is failed
msg:'success'
},
webPush: {
code:1, // 0 webpush is not available (browser does not support it) 1 is available 2 permission is disabled 3 permission is not confirmed
msg:'success'
}
}
- WebPush status codes:
The following status codes apply to getPushAuthority().webPush.code and webPushcallback(code, tip). They are independent of the initialization fail callback codes.
| code | msg | Remarks |
|---|---|---|
| 0 | The browser does not support the Notifications API | Browser does not support the Notifications API |
| 1 | Notification permissions available, message subscription successful. | Notification permission granted and subscription successful |
| 2 | Notification permissions have been disabled, message subscription failed. | Notification permission denied; subscription failed |
| 3 | Notification permissions have not been confirmed, message subscription has not been performed. | Notification permission not confirmed; no subscription performed |
| -1 | The browser does not support Service Worker. | Browser does not support Service Worker |
| -2 | Service Worker does not support HTTP. | Service Worker cannot run over HTTP |
| -3 | Service Worker registration failed. | Service Worker registration failed |
| -4 | Notification permission is available, but message subscription failed. | Notification permission granted, but subscription failed |
| -5 | Subscription has been canceled | Subscription canceled |
Obtain browser notification permission
window.MTpushInterface.getWebPermission()
Return parameter description
- granted : available
- denied : disabled
- default: permission not confirmed
Custom Message Reporting
If custom messages need to be reported for statistics, use the custom reporting APIs.
Display report:
window.MTpushInterface.customDisplayReport('msg_id');//msg_id is the msg_id of the custom message
Click report:
window.MTpushInterface.customClickReport('msg_id');//msg_id is the msg_id of the custom message
Disconnect monitoring
Interface Description
If disconnection occurs after successful initialization, the SDK will automatically try to reconnect and sign. It is recommended to call this event listener before initialization, and call initialization again after receiving this event.
window.MTpushInterface.mtPush.onDisconnect(fn)
call example
window.MTpushInterface.mtPush.onDisconnect(function () {
});
Cancel browser subscription
Unsubscribe from notifications. This method can be used when you do not need to receive notifications when you log out of an account when the privacy level of some accounts is high.
MTpushInterface. unSubscribe();
Set TagsAlias
window.MTpushInterface.setTagsAlias({})
MTpushInterface.setTagsAlias({ tags: ["test1", "test2"], alias: "aliass" });
Parameter Description
| Parameter name | Parameter type | Parameter description |
|---|---|---|
| tags | string[] | Mandatory, the maximum length of the array is 1000, and each element has a maximum of 40 characters |
| alias | string | required, maximum 40 characters |
Interface Description
Developers can set tags and alias through this interface. Note that this interface uses overwrite logic — setting an empty string will delete the existing tags and alias.
Set Notification Language
MTpushInterface.setLan(lan)
MTpushInterface.setLan(lan, (err) => {
alert(err ? "Failed to set notification language: " + err : "Notification language set successfully");
});
Parameter Description
| Parameter name | Parameter type | Parameter description |
|---|---|---|
| Parameter 1 | string | Required. Language parameter in ISO 639-1 language code format, for example "cn" for Chinese, "en" for English, and "ja" for Japanese |
| Parameter 2 | Function | Optional callback. It is called after setting is complete. The err parameter contains error information if any; no err means success |
Interface Description
Developers can use this API to manually set the notification language. After the setting succeeds, the SDK saves the language. If userLang is not passed during the next initialization, the locally saved language is used first.
Multiple Display of Category Prompts
window.MTpushInterface.promptPushCategories();
Interface Description
After the user subscribes to push notifications, developers can display category prompts multiple times as needed. This needs to be called after the SDK is initialized.
Safari Callback Compatibility
Starting with SDK v3.3.8, the push channel is selected according to the Safari subscription type. Callback availability depends on the subscription type, the page state when the event occurs, and when the listener is registered:
| Subscription or page state | Display callback | Click callback |
|---|---|---|
Legacy Safari Website Push subscription with an existing legacy deviceToken |
No reliable page-side display callback | No reliable page-side click callback |
| W3C Push subscription with an open page controlled by the Service Worker when the event occurs | Can fire when the message arrives | Can fire when the user clicks the notification |
| W3C Push subscription without a page that can receive messages when the event occurs | Does not fire and is not replayed after a page opens | Does not fire; the notification can still open the target page, but the callback is not replayed there |
| Listener registered after the event | Not replayed | Not replayed |
Page-side callbacks, system notification display, and server-side reporting are independent mechanisms. A missing page-side callback does not mean that the notification was not displayed or that delivery, display, or click data was not recorded by the server.
Push Message Display Callback
Interface Description
It is recommended to call the message listener before initialization.
Call Example
window.MTpushInterface.onMsgDisplay((msgData) => {});
Parameter Description
Notification message callback parameter msgData description:
{
engagelab_ntf_or_msg: number;
engagelab_appkey: string;
engagelab_passwd: string;
engagelab_uid: number;
engagelab_m_str: string;
engagelab_a_str: string;
type: number;
title: string;
content: string;
msg_id: string;
}
In-app message callback parameter msgData description:
{
title: string;
content: string;
msg_id: string;
ntf_or_msg: number;
type: number;
}
These types describe the standard in-app template provided by the console, where type is the number 0. A custom HTML template defines its own callback data.
Note:
In HTML editing mode for in-app messages, the callback parameters
titleandcontentare empty strings.Safari callbacks are subject to the compatibility conditions above. Register the listener before SDK initialization and ensure that a page controlled by the Service Worker exists when the event occurs.
Push Message Click Callback
Interface Description
It is recommended to call the message listener before initialization.
Call Example
window.MTpushInterface.onMsgClick((msgData) => {});
Parameter Description
Notification message callback parameter msgData description:
{
engagelab_ntf_or_msg: number;
engagelab_appkey: string;
engagelab_passwd: string;
engagelab_uid: number;
engagelab_m_str: string;
engagelab_a_str: string;
type: number;
title: string;
content: string;
msg_id: string;
target_event: string | null;
position: string; // Click position, 'msgBody' | Button ID
}
In-app message callback parameter msgData description:
{
position: 'msgBody' | 'mainBtn' | 'subBtn' | 'closeBtn';
msg_id: number;
title: string;
content: string;
extras: object | null;
ntf_or_msg: number;
strategy: object | null;
target_event: unknown[];
type: number;
icon: string;
}
Note:
- In HTML editing mode for in-app messages, the value of
positionis determined by the developer, and the callback parameterstitleandcontentare empty strings.- Safari callbacks are subject to the compatibility conditions above. If no page can receive messages when the notification is clicked, opening the target page does not replay the click callback.
error code
The table below lists the outer data.code values returned by initialization callbacks. Specific server initialization failures are reported in data.content.code. The same number can have different meanings in these two fields.
| code | message | Meaning |
|---|---|---|
| 0 | success | call succeeded |
| 1000 | unknown error | Unknown error. If content is do not support websocket, the browser does not support WebSocket. |
| 1001 | initing , please try again later | initializing, please try again later |
| 1002 | invalid config | Initial configuration error |
| 1003 | init failed | Initialization failed. Check the callback content and console output; see Server initialization error codes for content.code. |
| 1004 | init timeout | initialization timeout |
| 1005 | network error | network error, no network or cannot connect to websocket |
| 1006 | failed to get baseUrl and reportUrl | The get-webaddr API request failed, please refer to the content field in the callback for details |
| 1007 | authentication failed | Authentication failed. content contains the authentication API error description or network error information; see Authentication failures. |
| 1008 | region restricted | Region restricted. The SDK converts authentication API code 7017 to this code, with content set to REGION_RESTRICTED. |
Server initialization error codes
When initialization fails, the SDK returns an outer error code through fail (for example, data.code === 1003). If data.content is an object, data.content.code contains the specific server error code and data.content.desc contains its description, if provided.
Initialization validation and service errors
| content.code | Meaning | Recommended action |
|---|---|---|
| 4000 | Invalid initialization parameters | Check AppKey, user_str, and authentication parameters. Use the authentication data obtained by the SDK without modifying it manually. |
| 4003 | Authentication signature expired or timestamp outside the valid range | Obtain fresh authentication data and initialize again. Check the clock on the server generating the data; its timestamp must be within 30 minutes of the server’s current time. |
| 4005 | Signature verification failed | Ensure AppKey matches the authentication data. For a custom authentication service, check the signing algorithm and key configuration. |
| 4006 | Application does not exist | Check AppKey, whether the application was deleted, and whether the connection uses the application’s data center. |
| 4008 | The application’s WebPush VIP service has expired, so the server rejects initialization | Check the WebPush plan for this AppKey. Renew the service and initialize again. If the console still shows an active service, contact technical support to check the AppKey’s entitlements. |
| 5000 | Internal server error | Retry later. If the error persists, contact technical support with AppKey, the occurrence time, and the full error details. |
| 5001 | Server busy or timeout waiting for registration results | Wait before retrying and avoid frequent repeated initialization. Contact technical support if the error persists. |
For example, data.code === 1003 together with data.content.code === 4008 means initialization failed because the VIP service expired. Check both the outer code and the specific reason in content.
Error codes passed through from the registration service
When initialization requires user registration, the server also passes through registration service error codes. The table below lists compatibility mappings retained by the server; actual responses depend on the registration service version.
| content.code | Meaning | Recommended action |
|---|---|---|
| 11 | Internal server error | Retry later; contact technical support if the error persists. |
| 999 | Invalid parameters | Check initialization parameters and authentication data. |
| 1002 | Invalid parameters | Check initialization parameters and authentication data. |
| 1005 | AppKey not found | Check AppKey and the application’s data center. |
| 1006 | Application does not exist | Check AppKey and application status. |
| 1008 | Application does not exist | Check AppKey and application status. |
| 1009 | Application does not support the current platform | Ensure the application for this AppKey is configured for WebPush. |
| 1015 | Maximum user count exceeded | Contact technical support to check the application’s user limit. |
| 4001 | AppKey does not exist or signature verification failed | Check AppKey, authentication data, and signing configuration. |
| 4002 | User is not logged in | Initialize the SDK again; contact technical support if the error persists. |
| 4004 | Registration failed | Keep the full error details and retry later; contact technical support if the error persists. |
For example, outer data.code === 1008 means a region restriction, whereas outer code 1003 with inner data.content.code === 1008 means the application does not exist.
Authentication failures
If the authentication API fails, the SDK copies the response message into the data.content string. It does not return the original API code as content.code. Inspect the authentication request (/v1/auth) response in browser developer tools to find the original codes below.
| Original authentication API code | SDK callback data.code | Meaning and recommended action |
|---|---|---|
| 400 | 1007 | Business validation failed. APPKEY_NOT_FOUND means AppKey was not found. Other causes include a missing integration domain, a missing Origin header, or a mismatch between the request domain and application configuration. Check the specific content description. For Chrome extensions, also check the extension ID configuration. |
| 2002 | 1007 | Internal server error; callback content is inner err. Retry later and contact technical support if it persists. |
| 2003 | 1007 | Invalid parameters; callback content is param invalid. Check that AppKey and user_str were supplied. |
| 7017 | 1008 | Regional access restriction; callback content is REGION_RESTRICTED. Contact technical support to check the account’s regional access restrictions. |
Subscription expiration notification
The server sends 4107 (subscribe expired) through the WebSocket expired command when the browser push subscription expires. This is a system notification after initialization, not an initialization fail callback error. The SDK’s mtPush.onExpired listener receives the notification, but its callback does not include the error code.










