Logo Site EngageLab Mark Colored TransparentDocument
Search

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 { 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 }
              
              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 {
  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
}

            
This code block in the floating window
  • 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)
              
              window.MTpushInterface.init(Object:InitType)

            
This code block in the floating window

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](#error code)
message string result description
content string Return failure message when registration fails 1003

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"); } }); }, });
              
              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");
      }
    });
  },
});

            
This code block in the floating window

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()
              
              window.MTpushInterface.getRegistrationID()

            
This code block in the floating window

call example

var rid = window.MTpushInterface.getRegistrationID();
              
              var rid = window.MTpushInterface.getRegistrationID();

            
This code block in the floating window

stop push

Call this API to disconnect the push persistent connection established with the background and stop receiving push messages.

window.MTpushInterface.mtPush.stopPush()
              
              window.MTpushInterface.mtPush.stopPush()

            
This code block in the floating window

Push message monitoring

Interface Description

It is recommended to call the message listener before initialization.

window.MTpushInterface.onMsgReceive(fn)
              
              window.MTpushInterface.onMsgReceive(fn)

            
This code block in the floating window

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 } });
              
              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
   }

});

            
This code block in the floating window

return data

Parameter name Parameter type Parameter description
type number
  • 0: Engagelab channel message
  • 1: system channel message
  • 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()
                  
                  window.MTpushInterface.getPushAuthority()
    
                
    This code block in the floating window

    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' } }
                  
                  {
       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'
       }
    }
    
                
    This code block in the floating window
    • 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()
                  
                  window.MTpushInterface.getWebPermission()
    
                
    This code block in the floating window

    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
                  
                  window.MTpushInterface.customDisplayReport('msg_id');//msg_id is the msg_id of the custom message
    
                
    This code block in the floating window

    Click report:

    window.MTpushInterface.customClickReport('msg_id');//msg_id is the msg_id of the custom message
                  
                  window.MTpushInterface.customClickReport('msg_id');//msg_id is the msg_id of the custom message
    
                
    This code block in the floating window

    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)
                  
                  window.MTpushInterface.mtPush.onDisconnect(fn)
    
                
    This code block in the floating window

    call example

    window.MTpushInterface.mtPush.onDisconnect(function () { });
                  
                  window.MTpushInterface.mtPush.onDisconnect(function () {
    });
    
                
    This code block in the floating window

    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();
                  
                  MTpushInterface. unSubscribe();
    
                
    This code block in the floating window

    Set TagsAlias

    window.MTpushInterface.setTagsAlias({})

    MTpushInterface.setTagsAlias({ tags: ["test1", "test2"], alias: "aliass" });
                  
                  
    MTpushInterface.setTagsAlias({ tags: ["test1", "test2"], alias: "aliass" });
    
                
    This code block in the floating window

    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"); });
                  
                  MTpushInterface.setLan(lan, (err) => {
      alert(err ? "Failed to set notification language: " + err : "Notification language set successfully");
    });
    
                
    This code block in the floating window

    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();
                  
                  window.MTpushInterface.promptPushCategories();
    
                
    This code block in the floating window

    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) => {});
                  
                  window.MTpushInterface.onMsgDisplay((msgData) => {});
    
                
    This code block in the floating window

    Parameter Description

    Notification message callback parameter msgData description:

    { engagelab_ntf_or_msg: number; engagelab_appkey: string; engagelab_passwd: string; engagelab_uid: number; engagelab_mesg_type: string; engagelab_m_str: string; engagelab_a_str: string; type: number; title: string; content: string; msg_id: string; }
                  
                  {
      engagelab_ntf_or_msg: number;
      engagelab_appkey: string;
      engagelab_passwd: string;
      engagelab_uid: number;
      engagelab_mesg_type: string;
      engagelab_m_str: string;
      engagelab_a_str: string;
      type: number;
      title: string;
      content: string;
      msg_id: string;
    }
    
                
    This code block in the floating window

    In-app message callback parameter msgData description:

    { title: string; content: string; msg_id: string; ntf_or_msg: number; type: string; }
                  
                  {
      title: string;
      content: string;
      msg_id: string;
      ntf_or_msg: number;
      type: string;
    }
    
                
    This code block in the floating window

    Note:

    1. In HTML editing mode for in-app messages, the callback parameters title and content are empty strings.

    2. 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) => {});
                  
                  window.MTpushInterface.onMsgClick((msgData) => {});
    
                
    This code block in the floating window

    Parameter Description

    Notification message callback parameter msgData description:

    { engagelab_ntf_or_msg: number; engagelab_appkey: string; engagelab_passwd: string; engagelab_uid: number; engagelab_mesg_type: string; 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 }
                  
                  {
      engagelab_ntf_or_msg: number;
      engagelab_appkey: string;
      engagelab_passwd: string;
      engagelab_uid: number;
      engagelab_mesg_type: string;
      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
    }
    
                
    This code block in the floating window

    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; }
                  
                  {
      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;
    }
    
                
    This code block in the floating window

    Note:

    1. In HTML editing mode for in-app messages, the value of position is determined by the developer, and the callback parameters title and content are empty strings.
    2. 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
    1008 region restricted Region restricted
    Icon Solid Transparent White Qiyu
    Contact Sales