SDK

Device Registration

In this guide we will dive deeper into how you should handle the device registration. The very first time you instantiate our library we will automatically assign a device token to the browser, this will allow you to continue using all the functionality of Notificare until you actually decide you want to register for WebPush or Safari Website notifications. Obviously until you actually register for notifications, you'll not receive any remote notifications although messages might still end up in the in-app message inbox if implemented (and if you are not setting the configuration property ignoreNonWebPushDevices to true).

For your commodity, since 2.1.0, our library includes two new ways of automatically handling device registration for you after an user interaction. One of the launching modes available for you is the Floating Button:

document.addEventListener("DOMContentLoaded", () => {
    //This instantiates the library
    const notificare = new Notificare();
    notificare.launchWithFloatingButton({
        verticalAlignment: "bottom", //possible values top, bottom
        horizontalAlignment: "right", // possible values left, right
        permissionTexts: {
            default: "Click here to subscribe to remote notifications.",
            granted: "You are now subscribed to remote notifications",
            denied: "You've blocked notifications. Use the browser's settings to allow them."
        }
    });
});

This will display a button in your page at all times, where users can at any time subscribe for notifications. It will also display the notification's permission state when users have accepted or blocked notifications.

If for any reason you need to be informed when users click the button (while the permission state is default), you can implement the following callback function:

notificare.didClickFloatingButton = () => {
    // Triggered when users click the button while permission state is default
}

The other launching mode available for you is the Auto On-Boarding:

document.addEventListener("DOMContentLoaded", () => {
    //This instantiates the library
    const notificare = new Notificare();
    notificare.launchWithAutoOnBoarding({
        text: "Would you like to receive push notifications from our website?",
        cancelText: "No",
        acceptText: "Yes",
        retryAfterInterval: 1, //in hours, defaults to 24 hours if not present
        showAfterDelay: 10 //in seconds, defaults to immediately if not present
    });
});

The first time this method is invoked, it will show a modal window where users can choose to proceed and or cancel. If cancelled, we will not attempt to retry it until the retryAfterInterval period has been reached. If instead, users choose to accept it, the native permission dialog will be shown. If users still choose to block notifications this on-boarding modal will never be shown again.

If for any reason you need to be informed when users choose to accept or cancel the on-boarding window, the following callback functions are available:

notificare.didOpenNotificationPermission = () => {
    // Triggered when user accept to proceed and the native notification permission opens
}

notificare.didCancelOnBoarding = () => {
    // Triggered when user cancels on-boarding
}

If instead you would like to customize how the library is initialized and you want to design the user interaction yourself, you should wait until our library is fully initialized. Make sure you only call it after the onReady callback function is triggered:

document.addEventListener("DOMContentLoaded", () => {

    //This instantiates the library
    const notificare = new Notificare();

    notificare.launch(); // When launched for the first time Notificare will create a device token for this browser

    notificare.onReady = (application) => {
        notificare.registerForNotifications();
    }

});

The onReady callback method signals your website that the Notificare library has loaded its initial configuration and is ready to be used. Only after that, you should actually attempt to use any functionality of our library. Please note that this might not be the best experience for the user, it is also not permitted by some browsers (latest Safari for desktop), because invoking this method will trigger the permission dialog, it is important that is done by a user initiated gesture. Instead you will want to wait until you proper on-board a user, explain why you would like to use remote notifications, before you actually prompt the user with the remote notifications permission dialog. Take the following example in consideration:

...more code

const notificare = new Notificare();

// Let's check if remote notifications are supported and only launch if it is supported
// This will make sure that nothing is registered in Notificare if a browser does not support remote notifications
// Not required if allowOnlyWebPushSupportedDevices is set to true in your config.json
if (notificare.isWebPushSupported()) {
    notificare.launch();
}

// This example expects an element with an id named enableNotifications
let button = document.getElementById("enableNotifications");
button.style.display = 'none';

...more code

notificare.onReady = (application) => {

    //If it does let's check if it is already enabled
    if (notificare.isWebPushEnabled()) {

        //Remote notification are enabled already, proceed
        notificare.registerForNotifications();

    } else {
        //It's not let's on-board the user by showing the enable notifications button
        button.style.display = 'block';

        button.addEventListener('click', (e) => {
            e.preventDefault();
            notificare.registerForNotifications();
        });

    }
}

... more code

Whenever you invoke the notificare.registerForNotifications() method, our library will attempt to create a push subscription (for WebPush) or request a device token (for Safari WebsitePush) depending on the browser your visitor is using. If there is any problem with your the following callback function:

notificare.didFailToRegisterForNotifications = (error) => {
    //Handle this error accordingly
}

On the other end if your configuration is correct and a device is registered, it will trigger the following callback function:

notificare.didRegisterDevice = (device) => {
    //When triggered a device has been successfully registered
}

Please note that this callback method will also be trigger the very first time you instantiate the library assigning a device token to your browser, independently if you have invoked notificare.registerForNotifications().

If for any reason, the device registration fails, the following callback method will be triggered:

notificare.didFailToRegisterDevice = (error) => {
    //Handle error accordingly
}

But there will be situations where simply registering an anonymous device is not what you want. For example if you authenticate your users you will not want to register an anonymous device if the user is actually in an authenticated session in your website. When that is the case, you may want to register the device to a user profile like shown below:

notificare.registerDevice("MY_USER_ID", "MY_USER_NAME");

Although this is possible, it is not recommended. If you're going to use identifiers that are guessable or use personal data like an email. Due to the nature of javascript, doing this registration on the client-side is not secure and for most cases it will not be an option. If that is your case consider registering these user profiles using your server-side code and our REST API.

As soon as users are registered with Notificare, since 2.1.0, you can always check the permission state for notifications by invoking the following method:

let status = notificare.fetchWebPushPermission();

Override Device Language

By default we will automatically collect the language and region of a device based on the NSLocale of the device. For most cases this will be enough but for those cases where you would like to override the device language and region combination to a strict selection of languages, you can do so by invoking the following method:

notificare.updatePreferredLanguage("en-US").then((response) => {
    //Handle success
}).catch((e) => {
    //Handle error
});

Eventually you can always retrieve the preferred language by accessing the following property:

notificare.preferredLanguage;

User Data Fields

There are use cases where simply associating an userID and userName will not suffice. For those cases you can make use of User Data Fields where you can create key-value pairs for your application and then use them to extend your device registration. Before you can implement them you will need to first create them in your application via our dashboard. This is described here.

Once you have created one or more fields, you can implement this functionality in your app. To retrieve the list of fields allowed in your app you should use the following method:

notificare.fetchUserData().then((fields) => {
    console.log(fields);
}).catch((e) => {
    //Handle error
});

Whenever you want to update those fields with new values you should use the following method:

notificare.updateUserData([
    {
        key: "firstname",
        value: "John"
    }, {
        key: "lastname",
        value: "Doe"
    }
]).then((response) => {
    //Handle success
}).catch((e) => {
    //Handle error
});

If you are using our inbox functionality, these fields will also be available as placeholders when sending notifications by simply including {{userData.key}} in your messages. As with the registering user profiles, you may want to do this using your server-side code and our REST API.

Do Not Disturb

Each device registered with Notificare can be configured to specify a period of time during the day where it should not receive notifications. You can use this functionality in your website settings page to allow the user to provide a time range where messages will not be displayed generate an alert. Please note that if you are using our inbox functionality these message will still be visible there.

To retrieve a device's DnD preferences use the following method:

notificare.fetchDoNotDisturb().then((dnd) => {
    console.log(dnd);
}).catch((e) => {
    //Handle error
});

You can update the Do Not Disturb values for a device, using the following method:

notificare.updateDoNotDisturb("01:00", "07:00").then((dnd) => {
    console.log(dnd);
}).catch((e) => {
    //Handle error
});

Finally you will probably also need to eventually clear the Do Not Disturb period. To do that, simply use the method below:

notificare.clearDoNotDisturb().then((dnd) => {
    console.log(dnd);
}).catch((e) => {
    //Handle error
});

Disable Notifications

A good practice when using web push notifications is to allow the user to opt-out. Visitors are more likely to allow you to send push notifications if they can also quickly opt-out.

Pretty much the same way you subscribe a device for WebPush or Safari Website Push, you will also be able to unsubscribe. To do that, consider the following example:

...more code
button.addEventListener('click', (e) => {
    e.preventDefault();
    notificare.unregisterForNotifications();
});

Invoking this method will remove the subscription for web push notifications (if applicable) and assign a new token to the device. This will mean that you can still keep using all the other features of Notificare but obviously the user will not receive remote notifications anymore. You can at any point register for notifications again if you wish.

Un-launch Notificare

Finally, it is also possible to completely remove all data for a device, both locally in your app and remotely in our servers. To do that, use the following method:

notificare.unlaunch();

After invoking this, all the device's data will be destroyed and cannot be undone. Also, invoking any other method in Notificare will fail and the only way to start using the SDK again, is by invoking its counterpart, the launch method.