Web SDK API

最新の更新:2024-09-18

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 the 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 application appkey registered by the developer on the URORA platform, required user_str: string; //User unique ID, required swUrl?: string; //default "/sw.min." + sdkEnv.version + ".js" debugMode?: boolean; //default false, webSocketUrl?: string; //Use baseUrl if it does not exist 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 when the custom prompt is available, call Callback after the operation is completed to apply }
          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 application appkey registered by the developer on the URORA platform, required
   user_str: string; //User unique ID, required
   swUrl?: string; //default "/sw.min." + sdkEnv.version + ".js"
   debugMode?: boolean; //default false,
   webSocketUrl?: string; //Use baseUrl if it does not exist
   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 when the custom prompt is available, call Callback after the operation is completed to apply
}

        
このコードブロックは、フローティングウィンドウに表示されます

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)

        
このコードブロックは、フローティングウィンドウに表示されます

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

        
このコードブロックは、フローティングウィンドウに表示されます

call example

var rid = window.MTpushInterface.getRegistrationID();
          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()
          window.MTpushInterface.mtPush.stopPush()

        
このコードブロックは、フローティングウィンドウに表示されます

Push message monitoring

Interface Description

It is recommended to call the message listener before initialization.

window.MTpushInterface.onMsgReceive(fn)
          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 } });
          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
  • 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()
    
            
    このコードブロックは、フローティングウィンドウに表示されます

    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'
       }
    }
    
            
    このコードブロックは、フローティングウィンドウに表示されます

    Obtain browser notification permission

    window.MTpushInterface.getWebPermission()
              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
              
    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)
              window.MTpushInterface.mtPush.onDisconnect(fn)
    
            
    このコードブロックは、フローティングウィンドウに表示されます

    call example

    window.MTpushInterface.mtPush.onDisconnect(function () { });
              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();
              MTpushInterface. unSubscribe();
    
            
    このコードブロックは、フローティングウィンドウに表示されます

    Set TagsAlias

    window.MTpushInterface.setTagsAlias({})

    MTpushInterface.setTagsAlias({ tags: ["test1", "test2"], alias: "aliass" });
              
    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();
              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.

    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
    在文档中心打开
    icon
    営業に連絡する