Logo Site EngageLab Mark Colored Transparent文件
搜尋

Web SDK API

鑒權

開發者在執行初始化的時候,需要傳入必要信息,該數據結構由開發者服務端生成並傳回瀏覽器,用於開發者授權此瀏覽器運行的 MTpush 初始化。開發者需確保能調用獲取到此數據的皆為合法用戶。

初始化數據結構

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; // 统计上报地址,私有云或自定义部署场景使用 baseUrl?: string; // 服务器域名;与 report_url 同时存在时走私有云或自定义部署逻辑 userLang?: string; // 默认取浏览器当前的 navigator.language,必须是浏览器支持的语言值 safari_url?: string; // Safari 推送测试字段 appkey: string; // 开发者在 EngageLab 平台注册的应用 appkey,必填 user_str: string; // 用户唯一标识,必填 swUrl?: string; // 默认 "/sw" + sdkEnv.prefix is_temporary?: "n" | "t"; // 默认 "n" debugMode?: boolean; // 默认 false webSocketUrl?: string; // 如果不存在则用 baseUrl fail?: (data: dataType | undefined) => void; // 初始化失败回调 success?: (data: dataType | undefined) => void; // 初始化成功回调 webPushcallback?: def; canGetInfo?: (d: MTInitInfo) => void; custom?: (Callback: () => void) => void; // 自定义提示可用时回调,调用 Callback 可申请通知权限 maOpen?: boolean; // 是否开启 ma-sdk 模块 maChannel?: string; // ma-sdk 使用的渠道名称,默认值为 default-channel appName?: string; // ma-sdk 使用的网站名称,用于上报 userIdentity?: { userId?: string; anonymousId?: string }; // ma-sdk 使用的用户身份 maCompletion?: (code: number, msg: string) => void; // ma-sdk 初始化完成回调 openUrl?: string; // 点击通知时的跳转链接 encodeSwUrl?: boolean; // 是否对 swUrl 进行编码 regidSearchPath?: string; // 查询 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; // 统计上报地址,私有云或自定义部署场景使用
  baseUrl?: string; // 服务器域名;与 report_url 同时存在时走私有云或自定义部署逻辑
  userLang?: string; // 默认取浏览器当前的 navigator.language,必须是浏览器支持的语言值
  safari_url?: string; // Safari 推送测试字段
  appkey: string; // 开发者在 EngageLab 平台注册的应用 appkey,必填
  user_str: string; // 用户唯一标识,必填
  swUrl?: string; // 默认 "/sw" + sdkEnv.prefix
  is_temporary?: "n" | "t"; // 默认 "n"
  debugMode?: boolean; // 默认 false
  webSocketUrl?: string; // 如果不存在则用 baseUrl
  fail?: (data: dataType | undefined) => void; // 初始化失败回调
  success?: (data: dataType | undefined) => void; // 初始化成功回调
  webPushcallback?: def;
  canGetInfo?: (d: MTInitInfo) => void;
  custom?: (Callback: () => void) => void; // 自定义提示可用时回调,调用 Callback 可申请通知权限
  maOpen?: boolean; // 是否开启 ma-sdk 模块
  maChannel?: string; // ma-sdk 使用的渠道名称,默认值为 default-channel
  appName?: string; // ma-sdk 使用的网站名称,用于上报
  userIdentity?: { userId?: string; anonymousId?: string }; // ma-sdk 使用的用户身份
  maCompletion?: (code: number, msg: string) => void; // ma-sdk 初始化完成回调
  openUrl?: string; // 点击通知时的跳转链接
  encodeSwUrl?: boolean; // 是否对 swUrl 进行编码
  regidSearchPath?: string; // 查询 Registration ID 的页面路径
}

            
此代碼塊在浮窗中顯示
  • 參數說明:
    • openUrl:點擊通知時開啟的位址
      • 若發送通知時未指定開啟位址,則將使用本參數的值作為跳轉連結;
      • 若該參數未設定,則會預設跳轉至整合網域;
      • 在多網域整合場景下,該參數可實現向對應位址的跳轉;
    • encodeSwUrl:是否對 swUrl 進行編碼
      • 使用場景:若 swUrl 中含有 @ 等特殊符號,且伺服器限制了此 url 資源的存取,會導致 Service Worker 註冊失敗;需增加重新註冊 Service Worker 的機制,重試時將 swUrl 進行編碼。
    • regidSearchPath:用於指定查詢 Registration ID 的頁面路徑,預設值為 /engagelab/regid,詳見文檔 Registration ID 查詢功能使用指南

同一範圍只能註冊一個 service worker。當初始化成功時報錯,類似於 Failed to execute 'subscribe' on 'PushManager': Subscription failed - no active Service Worker 的錯誤,確認是否有 service worker 衝突,需合併 service worker 或解決 service worker 的作用域衝突。

SDK 初始化

接口說明

初始化接口。

window.MTpushInterface.init(Object:InitType)
              
              window.MTpushInterface.init(Object:InitType)

            
此代碼塊在浮窗中顯示

參數說明

參數名稱 參數類型 參數說明
code number 返回碼,0 代錶成功,其他失敗,詳見 錯誤碼
message string 結果描述
content string 註冊失敗 1003 時返回失敗信息

調用示例

const appkey = "your_appkey"; const userStr = "adminDemo"; MTpushInterface.init({ appkey: appkey, user_str: userStr, fail(data) { console.log("在线推送创建失败", data); }, success(data) { console.log("在线推送创建成功", data); }, webPushcallback(code, tip) { console.log("状态码及提示", code, tip); }, canGetInfo(data) { // 此时可以得到 RegId,也可以在 data 中取得初始化配置数据 console.log("得到 RegId", MTpushInterface.getRegistrationID(), data); // MTpushInterface.setTagsAlias({ tags: ["test1", "test2"], alias: "swefgwwefwfwfwf" }); }, custom: (requestPermission) => { // 使用自定义提示配置时,在合适的用户操作时机调用 requestPermission 请求通知权限 document.getElementById("subscribe")?.addEventListener("click", () => { if (Notification.permission === "default") { requestPermission(); } else if (Notification.permission === "denied") { console.log("通知权限已禁用,无法申请权限"); } else { console.log("已有通知权限,无需重复申请"); } }); }, });
              
              const appkey = "your_appkey";
const userStr = "adminDemo";

MTpushInterface.init({
  appkey: appkey,
  user_str: userStr,
  fail(data) {
    console.log("在线推送创建失败", data);
  },
  success(data) {
    console.log("在线推送创建成功", data);
  },
  webPushcallback(code, tip) {
    console.log("状态码及提示", code, tip);
  },
  canGetInfo(data) {
    // 此时可以得到 RegId,也可以在 data 中取得初始化配置数据
    console.log("得到 RegId", MTpushInterface.getRegistrationID(), data);
    // MTpushInterface.setTagsAlias({ tags: ["test1", "test2"], alias: "swefgwwefwfwfwf" });
  },
  custom: (requestPermission) => {
    // 使用自定义提示配置时,在合适的用户操作时机调用 requestPermission 请求通知权限
    document.getElementById("subscribe")?.addEventListener("click", () => {
      if (Notification.permission === "default") {
        requestPermission();
      } else if (Notification.permission === "denied") {
        console.log("通知权限已禁用,无法申请权限");
      } else {
        console.log("已有通知权限,无需重复申请");
      }
    });
  },
});

            
此代碼塊在浮窗中顯示

獲取 RegistrationID

接口說明

調用此 API 來取得當前賬戶對應的 RegistrationID。 隻有初始化簽名成功後才返回對應的值,否則返回空字符串。該方法需在 canGetInfo 回調觸發後調用。

window.MTpushInterface.getRegistrationID()
              
              window.MTpushInterface.getRegistrationID()

            
此代碼塊在浮窗中顯示

調用示例

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

            
此代碼塊在浮窗中顯示

停止推播

調用此 API 來斷開與後台建立的推播長連接,停止接收推播訊息。

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

            
此代碼塊在浮窗中顯示

推播訊息監聽

接口說明

建議在初始化前調用訊息監聽。

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

            
此代碼塊在浮窗中顯示

參數說明

參數名稱 參數類型 參數說明
fn function 訊息接收處理函數

調用示例

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
  }

});

            
此代碼塊在浮窗中顯示

返回數據

參數名稱 參數類型 參數說明
type number
  • 0 : Engagelab 通道訊息
  • 1 :係統通道訊息
  • data Object 訊息內容

    Engagelab 通道訊息數組(messages)

    參數名稱 參數類型 參數說明
    msg_id string 訊息 ID
    title string 訊息標題
    content string 訊息內容
    extras Object 訊息附加字段

    係統通道訊息數據

    支持 w3c interface NotificationOptions,詳見 mdn web docs

    檢查推播服務狀態

    window.MTpushInterface.getPushAuthority()
                  
                  window.MTpushInterface.getPushAuthority()
    
                
    此代碼塊在浮窗中顯示

    返回數據結構為如下:

    { mtPush:{ code:1, //1 成功,-1 初始化中,0 失敗 msg:'成功' }, webPush:{ code:1, // 0 webpush 不可用(瀏覽器不支持), 1 可用, 2 權限已被禁用, 3 權限冇確認 msg:'成功' } }
                  
                  {
      mtPush:{
        code:1, //1 成功,-1 初始化中,0 失敗
        msg:'成功'
      },
      webPush:{
        code:1, // 0 webpush 不可用(瀏覽器不支持), 1 可用, 2 權限已被禁用, 3 權限冇確認
        msg:'成功'
      }
    }
    
                
    此代碼塊在浮窗中顯示
    • 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 已取消訂閱

    獲取瀏覽器通知權限

    window.MTpushInterface.getWebPermission()
                  
                  window.MTpushInterface.getWebPermission()
    
                
    此代碼塊在浮窗中顯示

    返回參數說明

    • granted :可用
    • denied :禁用
    • default:權限冇確認

    自訂訊息打點

    自訂訊息如需上報做數據統計,請使用自訂上報接口。

    展示上報:

    window.MTpushInterface.customDisplayReport('msg_id');//msg_id為自訂訊息的msg_id
                  
                  window.MTpushInterface.customDisplayReport('msg_id');//msg_id為自訂訊息的msg_id
    
                
    此代碼塊在浮窗中顯示

    點擊上報:

    window.MTpushInterface.customClickReport('msg_id');//msg_id為自訂訊息的msg_id
                  
                  window.MTpushInterface.customClickReport('msg_id');//msg_id為自訂訊息的msg_id
    
                
    此代碼塊在浮窗中顯示

    斷線監聽

    接口說明

    初始化成功後出現斷線,SDK 會自動嘗試重連和簽名。 建議在初始化前調用此事件監聽,收到此事件請重新調用初始化。

    window.MTpushInterface.mtPush.onDisconnect(fn)
                  
                  window.MTpushInterface.mtPush.onDisconnect(fn)
    
                
    此代碼塊在浮窗中顯示

    調用示例

    window.MTpushInterface.mtPush.onDisconnect(function () { });
                  
                  window.MTpushInterface.mtPush.onDisconnect(function () {
    });
    
                
    此代碼塊在浮窗中顯示

    取消瀏覽器訂閱

    取消通知訂閱,某些帳號隱私等級較高情況下,退出帳號時不需要通接收知時可使用該方法。

    MTpushInterface.unSubscribe();
                  
                  MTpushInterface.unSubscribe();
    
                
    此代碼塊在浮窗中顯示

    設置 TagsAlias

    window.MTpushInterface.setTagsAlias({});
                  
                  window.MTpushInterface.setTagsAlias({});
    
                
    此代碼塊在浮窗中顯示
    MTpushInterface.setTagsAlias({ tags: ["test1", "test2"], alias: "aliass" });
                  
                  MTpushInterface.setTagsAlias({ tags: ["test1", "test2"], alias: "aliass" });
    
                
    此代碼塊在浮窗中顯示

    參數說明

    參數名稱 參數類型 參數說明
    tags string[] 必填,數組最大長度為 1000,每個元素最多 40 個字符
    alias string 必填,最多 40 個字符

    接口說明

    開發者可透過該介面設置 tag 和 alias,注意該介面是覆蓋邏輯,設置為空字串即刪除已有的 tag 和 alias。

    設置通知語言

    MTpushInterface.setLan(lan)

    MTpushInterface.setLan(lan, (err) => { alert(err ? "設置通知語言失敗:" + err : "設置通知語言成功"); });
                  
                  MTpushInterface.setLan(lan, (err) => {
      alert(err ? "設置通知語言失敗:" + err : "設置通知語言成功");
    });
    
                
    此代碼塊在浮窗中顯示

    參數說明

    參數名稱 參數類型 參數說明
    參數一 string 必填,語言參數,格式為 ISO 639-1 語言代碼,例如中文為 "cn",英文為 "en",日文為 "ja" 等
    參數二 Function 可選,回調函數,設置完成後會被調用,形參 err 為錯誤資訊(如果有的話),不存在形參則是成功

    接口說明

    開發者可透過該接口手動設置通知語言。設置成功後,SDK 會保存該語言;下次初始化未傳 userLang 時會優先使用本地保存的語言。

    多次顯示類別提示

    window.MTpushInterface.promptPushCategories();
                  
                  window.MTpushInterface.promptPushCategories();
    
                
    此代碼塊在浮窗中顯示

    接口說明

    在用戶訂閱推送後,開發者可以根據需要多次顯示類別提示,需要在初始化SDK完成後調用。

    推送消息展示回調

    接口說明

    建議在初始化前調用消息監聽。

    調用示例

    window.MTpushInterface.onMsgDisplay((msgData) => {});
                  
                  window.MTpushInterface.onMsgDisplay((msgData) => {});
    
                
    此代碼塊在浮窗中顯示

    參數說明

    通知消息回調參數 msgData 說明:

    { 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;
    }
    
                
    此代碼塊在浮窗中顯示

    應用內消息回調參數 msgData 說明:

    { 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;
    }
    
                
    此代碼塊在浮窗中顯示

    注意: 1、應用內消息 HTML 編輯模式下,展示回調的參數 title、content 為空字符串 2、safari 瀏覽器使用系統通道下發消息,無法得到消息的展示回調

    推送消息點擊回調

    接口說明

    建議在初始化前調用消息監聽。

    調用示例

    window.MTpushInterface.onMsgClick((msgData) => {});
                  
                  window.MTpushInterface.onMsgClick((msgData) => {});
    
                
    此代碼塊在浮窗中顯示

    參數說明

    通知消息回調參數 msgData 說明:

    { 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; // 點擊位置,'msgBody' | 按鈕的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; // 點擊位置,'msgBody' | 按鈕的id
    }
    
                
    此代碼塊在浮窗中顯示

    應用內消息回調參數 msgData 說明:

    { 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;
    }
    
                
    此代碼塊在浮窗中顯示

    注意:

    1、應用內消息HTML編輯模式,position 的值由開發者決定,點擊回調的參數 title、content 為空字符串。 2、safari 瀏覽器使用系統通道下發消息,無法得到消息的點擊回調。

    錯誤碼

    code message 備註
    0 success 調用成功
    1000 unknown error 未知錯誤
    1001 initing , please try again later 正在初始化,稍後再試
    1002 invalid config 初始化配置錯誤
    1003 init failed 初始化失敗,詳情參考控製台列印
    1004 init timeout 初始化超時
    1005 network error 網路錯誤,無網路或者連接不上 websocket
    1006 failed to get baseUrl and reportUrl 接口get-webaddr請求失敗,詳情參考回調中的content字段
    1007 authentication failed 鑒權失敗,詳情參考回調中的content字段
    1008 region restricted 區域受限
    Icon Solid Transparent White Qiyu
    聯繫銷售