2017-09-26 73 views
0

後我使用OneSignal得到通知,所以要根據文檔我做我的SDK代碼:獲取OneSignal用戶名認購

<script src="https://cdn.onesignal.com/sdks/OneSignalSDK.js" async></script> 
<script> 
var OneSignal = window.OneSignal || []; 
    OneSignal.push(["init", { 
     appId: "myappID", 
     safari_web_id: "myID", 
     autoRegister: false, 
     promptOptions: { 
      /* My prompt options */ 
     }, 
     welcomeNotification: { 
      //my options 
     }, 
     notifyButton: { 
     enable: true, 
     showCredit: false, 
     prenotify: true, 
     position: 'bottom-left', 
     text: { 
      /*My text options */ 
     }, 
     colors: { // My custom colors 
     } 
     } 
    }]); 

    OneSignal.push(function(){ 
     OneSignal.showHttpPrompt(); 

     OneSignal.getUserId().then(function(userId){ 
      console.log("OneSignal User ID:", userId); 
     }); 
    }); 
</script> 

它的偉大工程幻燈片顯示提示信息,但訂閱後,我需要刷新網站以在控制檯中獲取用戶ID。如何修改此代碼函數以在訂閱後立即在控制檯中獲取用戶ID?

回答

1

您需要爲訂閱更改事件添加偵聽器。否則,getUserId調用將在用戶接受訂閱之前觸發。這對我很有用:

var OneSignal = window.OneSignal || []; 

OneSignal.push(function() { 
    OneSignal.on('subscriptionChange', function (isSubscribed) { 
    console.log("The user's subscription state is now:",isSubscribed); 
     OneSignal.push(function() { 
     OneSignal.getUserId(function(userId) { 
      console.log("OneSignal User ID:", userId); 
     }); 
     }); 
    }); 
    }); 

    OneSignal.push(["init", { 
    appId: "myappID", 
    safari_web_id: "myID", 
    autoRegister: false, 
    promptOptions: { 
     /* My prompt options */ 
    }, 
    welcomeNotification: { 
     //my options 
    }, 
    notifyButton: { 
     enable: true, 
     showCredit: false, 
     prenotify: true, 
     position: 'bottom-left', 
     text: { 
     /*My text options */ 
    }, 
    colors: { // My custom colors 
    } 
    } 
}]);