Search code examples
push-notificationnotificationsonesignal

Get OneSignal UserID after subscribe


I'm using OneSignal to get notifications, so according to docs I made my SDK code like this:

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

It works great showing slideshow prompt message, but after subscribe I need to refresh the website to get UserID in console. How can I modify this code function to get userID in console immediately after subscribe?


Solution

  • You need to add a listener for the subscription change event. Otherwise the getUserId call will trigger before the user has accepted the subscription. This is working for me:

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