Initial SDK setup

Minimum setup

To get started, you need to perform the following tasks:

Supported browsers

FollowAnalytics SDK supports Web Analytics and sending Web Push Notifications to desktop or mobile browsers. Web Analytics works on the following browsers:

Web Push Notifications works on the following browsers:

Chrome, Firefox, Opera (both on Desktop and Android)

Future versions of the SDK will support Safari Push Notifications.

Install and configure with your API key

Prepare your API key

Be sure to have your API key for this step of the configuration. If you are not sure where to find it, please reach out to your Customer Success Manager or message support@followanalytics.com

  1. Download the SDK.

  2. Place the downloaded fa-sdk-web.js and fa-sw-webpush.js in your site's root.

  3. Copy this snippet into the <head></head> of your site/application and everywhere you want to use the FollowAnalytics Web SDK:

    &lt;script type="text/javascript" src="/fa-sdk-web.js"&gt;&lt;/script&gt;
    &lt;script type="text/javascript"&gt;
        FollowAnalytics.initialize({
            FAID: '&lt;YOUR_API_KEY&gt;',
            bundleId: '&lt;YOUR_BUNDLE_ID&gt;'
        });
    &lt;/script&gt;

Replace <YOUR_API_KEY> and <YOUR_BUNDLE_ID> with the API Key and Bundle ID you got from the Administration section on the FollowAnalytics platform.

You can pass a defaultIcon value to the initialize method to make sure your Push Notifications have an icon displayed by default. You can override this defaultIcon on a per-message basis from the Campaign creation section. Example usage of the defaultIcon parameter:

    &lt;script type="text/javascript" src="/fa-sdk-web.js"&gt;&lt;/script&gt;
    &lt;script type="text/javascript"&gt;
        FollowAnalytics.initialize({
            FAID: '&lt;YOUR_API_KEY&gt;',
            bundleId: '&lt;YOUR_BUNDLE_ID&gt;',
            defaultIcon: 'https://s3-eu-west-1.amazonaws.com/fa-sdks/sdk-web/web-sdk-assets/followanalytics192.png'
        });
    &lt;/script&gt;

Install using npm

You can use the FollowAnalytics Web SDK from npm. You can add it with npm install --save followanalytics.

We have three stages for the SDK, alpha, beta and stable. You can install each one of those by doing:

npm install --save followanalytics-alpha for the alpha version, an unstable version containing the latest developments.

npm install --save followanalytics-beta for the beta version, a version that is being tested and almost bug free.

npm install --save followanalytics for the latest release version.

Once the package is installed you just need to import it from one of your component or web page so it can be used. Check an example implementation inside a React application.

When using the FollowAnalytics Web SDK from npm you'll need to expose the Service Worker, located at node_modules/followanalytics/fa-sw-webpush.js to the browser as being served from the server's root. As an example, if your using an Expressjs application your route config should be something like this:

app.get('/fa-sw-webpush.js', function(req, res, next) {
    res.set('Content-Type', 'application/javascript');
    res.sendFile('./node_modules/followanalytics/lib/fa-sw-webpush.js' , { root : __dirname});
});

OptInAnalytics

You can configure the default state of analytics collection for your site or web application using the initialization parameter optInAnalytics.

When set to false no analytics data will be collected. You can change this at runtime by using FollowAnalytics.setOptInAnalytics(true).

Example, starting with no analytics collection:

    &lt;script type="text/javascript" src="/fa-sdk-web.js"&gt;&lt;/script&gt;
    &lt;script type="text/javascript"&gt;
        FollowAnalytics.initialize({
            FAID: '&lt;YOUR_API_KEY&gt;',
            bundleId: '&lt;YOUR_BUNDLE_ID&gt;',
            defaultIcon: 'https://s3-eu-west-1.amazonaws.com/fa-sdks/sdk-web/web-sdk-assets/followanalytics192.png'
            (...),
            optInAnalytics: false
        });
    &lt;/script&gt;

In order to enable analytics, call FollowAnalytics.setOptInAnalytics(true) from anywhere in your code.

Analytics Scope

You can configure the scope of the analytics for your site or web application by using the initialization parameter analyticsScope.

This method accepts 'FULL' or 'PUSH' as a value. When you chose 'PUSH' analytics collection will only take place if the user registers for Notifications. When the scope is set to 'FULL' analytics collection will take place, not depending of the user Notification acceptance.

You can only change this while in development. In order to change it you'll have to redeploy your code.

Example, starting with full analytics collection:

    &lt;script type="text/javascript" src="/fa-sdk-web.js"&gt;&lt;/script&gt;
    &lt;script type="text/javascript"&gt;
        FollowAnalytics.initialize({
            FAID: '&lt;YOUR_API_KEY&gt;',
            bundleId: '&lt;YOUR_BUNDLE_ID&gt;',
            defaultIcon: 'https://s3-eu-west-1.amazonaws.com/fa-sdks/sdk-web/web-sdk-assets/followanalytics192.png'
            (...),
            analyticsScope: FollowAnalytics.AnalyticsScope.FULL
        });
    &lt;/script&gt;

Or if you want to only collect analytics when the User registered for Notifications:

    &lt;script type="text/javascript" src="/fa-sdk-web.js"&gt;&lt;/script&gt;
    &lt;script type="text/javascript"&gt;
        FollowAnalytics.initialize({
            FAID: '&lt;YOUR_API_KEY&gt;',
            bundleId: '&lt;YOUR_BUNDLE_ID&gt;',
            defaultIcon: 'https://s3-eu-west-1.amazonaws.com/fa-sdks/sdk-web/web-sdk-assets/followanalytics192.png'
            (...),
            analyticsScope: FollowAnalytics.AnalyticsScope.PUSH
        });
    &lt;/script&gt;

GDPR and Privacy

To support privacy regulations, most notably GDPR, the EU’s General Data Protection Regulation as well as our customers’ privacy policy requirements, FollowAnalytics provides the methods to assist you in these obligations.

The following methods are available in the SDK:

        FollowAnalytics.GDPR.requestToDeleteMyData()
    FollowAnalytics.GDPR.requestToAccessMyData()

Both methods will only work if a userId is set for the current session.

FollowAnalytics.GDPR.requestToAccessMyData() - sends a request to FollowAnalytics' servers to download all user data for the current application.

FollowAnalytics.GDPR.requestToDeleteMyData() - sends a request to FollowAnalytics' servers to delete all user data for the current application.

Both these methods return a Promise. You can used them as follows:

        FollowAnalytics.GDPR.requestToDeleteMyData().then(function(result) {
        // successfull request
        console.log(result);
    }).catch(function(error) {
        // request failed
        console.log(error);
    });
    FollowAnalytics.GDPR.requestToAccessMyData().then(function(result) {
        // successfull request
        console.log(result);
    }).catch(function(error) {
        // request failed
        console.log(error);
    });

Data Wallet

The Data Wallet feature, available from FollowAnalytics' platform, allows our clients to create , edit and publish policies : Legal text, Data sources, Purposes.

In order to make these data available from our SDK the following methods were added:

    FollowAnalytics.DataWallet.getPolicy()
    FollowAnalytics.DataWallet.isRead();
    FollowAnalytics.DataWallet.setIsRead(true);

FollowAnalytics.DataWallet.getPolicy() - fetches the current privacy policy for the application from the FollowAnalytics platform.

FollowAnalytics.DataWallet.isRead() - allows you to check the state of the current privacy policy.

FollowAnalytics.DataWallet.setIsRead() - specifies the read state for the current privacy policy. After it has been read, call the method to mark it as read.

You can configure the SDK with the following parameters:

    isDataWalletEnabled: true,
    onDataWalletPolicyChange: function() {},

isDataWalletEnabled: true - allows you to enable/disable the DataWallet features.

onDataWalletPolicyChange: function() {} - this parameter requires a callback function and the implementation of a listener for the Policy change.

An example would be:

    &lt;script type="text/javascript" src="/fa-sdk-web.js"&gt;&lt;/script&gt;
    &lt;script type="text/javascript"&gt;
        FollowAnalytics.initialize({
            FAID: '&lt;YOUR_API_KEY&gt;',
            bundleId: '&lt;YOUR_BUNDLE_ID&gt;',
            defaultIcon: 'https://s3-eu-west-1.amazonaws.com/fa-sdks/sdk-web/web-sdk-assets/followanalytics192.png'
            (...),
            isDataWalletEnabled: true,
            onDataWalletPolicyChange: function() {
                                        if (confirm('Privacy Policy has changed')) {
                                            // User has read the Privacy policy (clicked OK). Mark it as read
                                            FollowAnalytics.DataWallet.setIsRead(true);
                                        } else {
                                            // User has not read the policy (clicked cancel)
                                        }
                                      },
        });
    &lt;/script&gt;

Service Worker

After downloading and extracting the FollowAnalytics Web SDK, you'll have a file named fa-sw-webpush.js. This file must be uploaded to the root of your site, so that it can be accessed by going to https://you_website.com/fa-sw-webpush.js. This is mandatory in order for Notifications to work.

Integrating with an existing Service Worker

As there can only be one Service Worker registered per domain, you'll have to load FollowAnalytics' Service Worker from inside your existing one. Save the downloaded fa-sw-webpush.js right next to the existing Service Worker file and add the following at the end: importScripts("./fa-sw-webpush.js");.

Caching

With the increase of Progressive Web Apps you may run into problems when updating the SDK files on your site. Please make sure you properly invalidate the cache for the SDK files after you update them. Otherwise, it may lead to unexpected results.

Register for notifications

Web push notifications require HTTPS

Web push notifications can only be sent if your web domain is accessible through HTTPS.

Optimize your subscription rate

You should explain to your visitors the benefit of registering to your notifications before prompting them the popup which formally collects the permission. A user is much more likely to accept notifications if they know what they will receive, how frequently, and so on.

A push notification is a message that appears on the user’s screen and can be received even when your web page is not currently open in the user's browser.

In order for your Web Push Notifications to work, you must register it by calling:

FollowAnalytics.registerForPushNotifications();

If a user wants to unsubscribe from Web Push Notifications, you can do so by calling:

FollowAnalytics.unregisterFromPushNotifications();

To check if a user is already registered for Push Notifications you can use the following method:

FollowAnalytics.isRegisteredForPushNotifications();

Logging

Logging best practices

To ensure your tags are relevant and will end up empowering your team through FollowAnalytics, please read the Logging best practices entry in the FAQ section.

Events vs Attributes

The FollowAnalytics SDK allows you to tag both events and attributes. If you are unsure about the difference, please refer to the corresponding FAQ entry.

Tag Events

The SDK allows you to log events happening in your code. These are the two methods you can call on the SDK:

FollowAnalytics.logEvent(name, arg)
FollowAnalytics.logError(name, arg)

Use the name as the unique identifier of your tag, use the details section to add context. Events can be renamed later: the name that you give to your event here can be overridden in the FollowAnalytics UI.

The details field can either be a String or a Hash, so that you can associate multiple key-values for additional context.

For instance, logging the appearance of a view could be done as the following examples:

FollowAnalytics.logEvent('Product view', 'Product reference')

var details = {firstParam: 'My first object detail', secondParam: 'My second object detail'}
FollowAnalytics.logEvent('Example log name', details)

User ID

If users can sign in somewhere in your web app, you can specify their identifier to the SDK. This way, you will be able to build a profile in FollowAnalytics, send transactional campaigns, link your users with your other apps and even between FollowAnalytics and your CRM, and more.

This identifier is usually an e-mail address, client identifier, phone number, or anything else that uniquely ties your customers to you. Keep in mind that you should only do this if it's crucial for your web page's behavior.

To register the user identifier, use:

Javascript

FollowAnalytics.setUserId('userId')

If you want to remove the user identifier (in case of a sign out for instance) use the following method:

FollowAnalytics.setUserId(null)

You can get the current user ID set by calling:

FollowAnalytics.getUserId()

User ID and attributes

You don't need a user ID to set attributes

Attributes are tied to the device when no user ID is provided. If a user ID is set, a profile is created and can be shared across apps.

In both cases, attributes can be used in segments and campaigns to target users.

User ID

If users can sign in somewhere in your app, you can specify their identifier to the SDK. This way, you will be able to relate crashes to specific users, link your users between FollowAnalytics and your CRM, and more.

This identifier is usually an e-mail address, client identifier, phone number, or anything else that uniquely ties your customers to you.

To register the user identifier, use:

FollowAnalytics.setUserId();

If you want to remove the user identifier (in case of a sign out for instance) use the following method:

FollowAnalytics.setUserId(null);

Predefined attributes

The SDK allows to set values for both custom and predefined attributes.

For predefined attributes, the SDK has the following properties:

FollowAnalytics.UserAttributes.setFirstName('MY_FIRST_NAME');
FollowAnalytics.UserAttributes.setLastName('MY_LAST_NAME');
FollowAnalytics.UserAttributes.setEmail('MY_FIRST_NAME@MY_DOMAIN.COM');
FollowAnalytics.UserAttributes.setDateOfBirth('2018-01-01');
FollowAnalytics.UserAttributes.setGender(FollowAnalytics.Gender.MALE);
FollowAnalytics.UserAttributes.setCountry('France');
FollowAnalytics.UserAttributes.setCity('Paris');
FollowAnalytics.UserAttributes.setRegion('Ile-de-France');
FollowAnalytics.UserAttributes.setProfilePictureUrl('https://lovely-profile-picture.com/awesome.jpg');

They are "predefined" in the sense that they will be attached to default fields on your user profiles.

For example, to set user Joe's city to "Paris", you would proceed as follows:

FollowAnalytics.UserAttributes.setFirstName("Joe");
FollowAnalytics.UserAttributes.setCity("Paris");

Custom attributes

Double check your custom attribute types

When a value for an unknown attribute is received by the server, the attribute is declared with the type of that first value.

If you change the type of an attribute in the SDK, values might be refused server-side. Please ensure the types match by visiting the profile data section of the product.

Set a custom attribute

To set your custom attributes, you can use methods that are adapted for each type:

FollowAnalytics.UserAttributes.setNumber(key, number);
FollowAnalytics.UserAttributes.setString(key, string);
FollowAnalytics.UserAttributes.setBoolean(key, boolean);
FollowAnalytics.UserAttributes.setDate(key, date);
FollowAnalytics.UserAttributes.setDateTime(key, datetime);

For example, to set the user's job:

FollowAnalytics.UserAttributes.setString('key_job', 'Taxi Driver');
Delete a custom attribute value

You can delete the value of an attribute by setting its value to null. For example, to delete the user's job:

FollowAnalytics.UserAttributes.setString("key_job", null);
Set of Attributes

You can add or remove an item to or from a set of attributes.

To add an item:

FollowAnalytics.UserAttributes.addToSet('fruits', 'apple');
FollowAnalytics.UserAttributes.addToSet('fruits', 'strawberry');
FollowAnalytics.UserAttributes.addToSet('fruits', 'lemon');

To add several items at once:

FollowAnalytics.UserAttributes.addToSet('fruits', 'apple', 'strawberry', 'lemon');

or passing an Array:

// don't use `[element1, element2]`, use `new Array(element1, element2)`)
FollowAnalytics.UserAttributes.addToSet('fruits', new Array('pear', 'strawberry', 'pineapple'));

To remove an item:

FollowAnalytics.UserAttributes.removeFromSet(key, 'lemon'); // Removes "lemon" from set of 'fruits'.

To remove several items at once:

FollowAnalytics.UserAttributes.removeFromSet('fruits', 'apple', 'strawberry', 'lemon');

or passing an Array:

// don't use `[element1, element2]`, use `new Array(element1, element2)`)
FollowAnalytics.UserAttributes.removeFromSet('fruits', new Array('pear', 'strawberry', 'pineapple'));

And to clear a set:

FollowAnalytics.UserAttributes.clearSet('fruits'); // Removes all the items from the set of 'fruits'.

Advanced use cases

Device ID

You can get your device ID, which is a unique identifier generated on the very first use of the SDK, and stored in local storage. As long as the user doesn't delete their local storage data, this value will prevail.

FollowAnalytics.getDeviceId()

This method will return a string containing the deviceId value.

Optional initialization parameters

When initializing the SDK in your web app, you can pass the following parameters to customize its behavior: