Menu

In this article we're going to see how to get and save the OneSignal's user ID with JavaScript.

This article assumes that you've already installed and configured the required SDK files on your server. Getting and saving an user's ID is really useful when you want to send a customized push notification to a specific user.

The first thing to do is to include the OneSignal's SDK:

<script src="https://cdn.onesignal.com/sdks/OneSignalSDK.js" async=""></script>

Then we can use the native localStorage object in order to store the user ID that we can retrieve with the getUserId() method.

 window.OneSignal = window.OneSignal || [];
        OneSignal.push(function() {
            OneSignal.init({
                appId: 'your-app-ID',
            });

        });
        OneSignal.push(function() {
           if(localStorage.getItem('os-user') === null) {
               OneSignal.getUserId(function(userId) {
                    localStorage.setItem('os-user', userId);
               });
           }
        });

Now the user ID is available in the browser's web storage and we can save it permanently into a database with AJAX or simply use it in our application.

Share: