Web SDK API
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,
message: string,
};
interface InitType {
appkey: string; //The appkey of the application registered on the URORA platform by the developer, required
user_str: string; //Unique identifier for the user, required
swUrl?: string; //Default "/sw.min." + sdkEnv.version + ".js"
debugMode?: boolean; //Default false
webSocketUrl?: string; //If not provided, baseUrl will be used
fail?: (data: dataType | undefined) => void; //Callback for initialization failure
success?: (data: dataType | undefined) => void; //Callback for successful initialization
webPushcallback?: def;
canGetInfo?: (d: MTInitInfo) => void;
custom?: (Callback: () => void) => void; //Callback for custom prompt availability, call Callback after operation to apply
maCompletion?: (code: number, msg: string) => void; //Callback for ma-sdk initialization completion
/**
* Redirect link when clicking on a notification, priority: URL set when sending notification -> InitType.openUrl -> domain of the integrated page
* For Safari browser, messages delivered through the system channel require additional handling: set window.MTpushInterfaceTempData = { openUrl: 'https://example.com' } before loading the SDK
*/
openUrl?: string;
/**
* Whether to encode swUrl
* Usage scenario:
* If swUrl contains special characters like @ and the server restricts access to this URL resource, it may cause Service Worker registration to fail;
* A mechanism to re-register the Service Worker is needed, and swUrl should be encoded during retries.
*/
encodeSwUrl?: boolean;
}
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](/zh_CN/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](#error code) |
| message | string | result description |
| content | string | Return failure message when registration fails 1003 |
call example
MTpushInterface.init({
appkey: "xxx",
user_str: "adminDemo",
fail(data) {
console.log("Failed to create online push", data);
},
success(data) {
console.log("Online push created successfully", data);
},
webPushcallback(cod, tip) {
console.log("The status code and prompt the user gets", code, tip);
},
//swUrl?: string; //default "/sw.min." + sdkEnv.version + ".js"
canGetInfo(d) {
//At this time, you can get the RegId or get all the data in d
console.log("Get RegId", MTpushInterface.getRegistrationID(), d);
// MTpushInterface.setTagsAlias({ tags: ["test1", "test2"], alias: "swefgwwefwfwfwf" });
},
custom: (reqPermission) => {
//When using a custom prompt configuration, you must call reqPermission to request and configure permissions. Obtain the request permission function in the custom callback and directly call reqPermission at the appropriate time to request notification permissions.
document.getElementById("xx")?.addEventListener("click", reqPermission); },
});
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對象的錯誤碼:
| code | msg | 備註 |
|---|---|---|
| 0 | The browser does not support the Notifications API | 瀏覽器不支持通知 API |
| 1 | Notification permissions available, message subscription successful. | 通知權限可用,消息訂閱成功 |
| 2 | Notification permissions have been disabled, message subscription failed. | 通知權限已被禁用,消息訂閱失敗 |
| 3 | Notification permissions have not been confirmed, message subscription has not been performed. | 通知權限尚未確認,未進行消息訂閱 |
| -1 | The browser does not support Service Worker. | 瀏覽器不支持 Service Worker |
| -2 | Service Worker does not support HTTP. | Service Worker 不支持 HTTP 協議 |
| -3 | Service Worker registration failed. | Service Worker 註冊失敗 |
| -4 | Notification permission is available, but message subscription failed. | 通知權限可用,但消息訂閱失敗 |
| -5 | Subscription has been canceled | 已取消訂閱 |
Obtain browser notification permission
window.MTpushInterface.getWebPermission()
Return parameter description
- granted : available
- denied : disabled
- default: permission not confirmed
Report custom message data
If you need to make data statistics of custom messages, please use the custom reporting interface to report data.
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 and delete tags under a specific alias through this interface. This interface is an overlay logic. If the notification is set to an empty string, existing tags can be deleted.
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.
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:
{
title: string;
content: string;
msg_id: string;
ntf_or_msg: number;
engagelab_appkey: string;
engagelab_passwd: string;
engagelab_uid: string;
engagelab_url: string;
type: string; // 0: Engagelab channel message 1: System channel message
}
In-app message callback parameter msgData description:
{
title: string;
content: string;
msg_id: string;
ntf_or_msg: number;
type: string;
}
Note:
In HTML editing mode for in-app messages, the callback parameters
titleandcontentare empty strings.Messages delivered via the system channel in the Safari browser cannot receive display callbacks.
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:
{
title: string;
content: string;
msg_id: string;
ntf_or_msg: number;
engagelab_appkey: string;
engagelab_passwd: string;
engagelab_uid: string;
engagelab_url: string;
position: string; // Click position, 'msgBody' | Button ID
type: string; // 0: Engagelab channel message 1: System channel message
}
In-app message callback parameter msgData description:
{
title: string;
content: string;
msg_id: string;
ntf_or_msg: number;
position: 'msgBody' | 'mainBtn' | 'subBtn' | 'closeBtn';
type: string;
}
Note:
- In HTML editing mode for in-app messages, the value of
positionis determined by the developer, and the callback parameterstitleandcontentare empty strings.- Messages delivered via the system channel in the Safari browser cannot receive click callbacks.
error code
| code | message | Remarks |
|---|---|---|
| 0 | success | call succeeded |
| 1000 | unknown error | unknown error |
| 1001 | initing , please try again later | initializing, please try again later |
| 1002 | invalid config | Initial configuration error |
| 1003 | init failed | Initialization failed, please refer to console printing for details |
| 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, please refer to the content field in the callback for details |









