Web
The Swrve Web SDK for web browsers enables your web app to use all of these features. This guide contains all the information you need to integrate the SDK for your web app.
Requirements
- The Swrve Web SDK is intended and tested for use with web browsers—mainly Chrome, Firefox, and Safari.
- To use the Swrve Web SDK, you must generate a Web SDK API key in Swrve on the app’s Integration Settings screen. For more information, see Integrate your app.
- The Swrve Web SDK is intended for tracking and targeting identified users across multiple channels and platforms, for example, web, mobile app, TV. Therefore, you must have your own means of generating and storing unique identifiers for the visitors of your site. For more information, see Tracking your users with Swrve User Identity.
- If you download the SwrveSDK production bundle and include it via script tag, there are no additional dependencies.
- If you want to compile the SDK bundle from source, you will need Node.js 10+ and Yarn 1.5+.
Installing the SDK
Swrve has an open source SDK repository. There are two options for downloading the latest public Swrve Web SDK:
- Install the SDK using npm (node package manager).
Run the following command:npm install @swrve/web-sdk. - Download the SDK from the GitHub public repository.
Initializing the SDK
To initialize the SDK, create an instance before your application starts. Replace <app_id>, <web_api_key> and <external_user_id> with your app ID, Web SDK API key and unique external user ID.
External user ID
The external user ID is a non-discoverable key that identifies your user across multiple channels and platforms. To ensure app security, Swrve does not accept email or other personally identifiable information (PIIs) as the external user ID and rejects them on the server side. Before you implement the Identify service, please consult with your CSM at support@messagegears.com for some guidance on best practices to follow in your integration.
The external user ID should always be unique to each user. Using a shared external user ID across users may have adverse consequences on user segmentation, reporting, audiences, and QA device behavior.
Using the SDK bundle with a script tag
<script src="SwrveSDK.js"></script>
<script>
SwrveSDK.default.initWithConfig({
appId: <app_id>,
apiKey: "<web_api_key>",
externalUserId: "<external_user_id>",
//stack: "eu", **To use the EU stack, include this in your config **//
});
</script>
.default is not necessary if you are using modules.Using the SDK when installed from npm
When using ES5 modules, require the SDK as follows:
var SwrveSDK = require("@swrve/web-sdk");
SwrveSDK.initWithConfig({
appId: <app_id>,
apiKey: "<web_api_key>",
externalUserId: "<external_user_id>",
//stack: "eu", **To use the EU stack, include this in your config **//
});
Or you can import it it as an ES6 module:
import SwrveSDK from "@swrve/web-sdk";
SwrveSDK.initWithConfig({
appId: <app_id>,
apiKey: "<web_api_key>",
externalUserId: "<external_user_id>",
//** stack: "eu", **To use the EU stack, include this in your config **//
});
Push notifications
Use Swrve’s web push notification campaigns to send personalized messages to your website users.
Supported browsers
Swrve web push notifications are available on the following browsers and operating systems.
| Browser | Android | iPhone | Mac OS X | Windows PC |
|---|---|---|---|---|
| Chrome | ✔ | ✖ | ✔ | ✔ |
| Firefox | ✔ | ✖ | ✔ | ✔ |
| Opera | ✔ | ✖ | ✖ | ✖ |
| Safari | ✖ | ✖ | ✔ | ✖ |
Web push integration steps
This section covers how to integrate Swrve web push notifications with your website.
Our web push system makes use of service workers. These are files that run on the browser to receive particular messages and are attached to the domain. To operate successfully, the service worker file must be at the root of your website package. We provide the service worker in our package under the name SwrveWorker.js. If you are directly downloading our library, you can copy it directly in. If you are using a package manager like npm, you can include a script in your package.json to move it after a successful install.
"scripts": {
"postinstall": "mv node_modules/@swrve/web-sdk/dist/SwrveWorker.js SwrveWorker.js"
},
Push notification registration is disabled by default. To enable it, in the initialization config set autoPushSubscribe to true.
SwrveSDK.initWithConfig({
appId: <app_id>,
apiKey: "<web_api_key>",
externalUserId: "<external_user_id>",
autoPushSubscribe: true,
serviceWorker: '../swrveWorker.js'
});
If you would prefer to start the registration yourself, do not include the autoPushSubscribe in your initialization config. Use with the following function instead:
/** In this example, we have two callback functions which can used to capture the status of the registration **/
var optionalOnSuccess = () => {
console.log('Subscribed to push successfully');
};
var optionalOnFailure = (error) => {
console.log('Failed to subscribe to push');
console.error(error);
};
SwrveSDK.registerPush(optionalOnSuccess, optionalOnFailure);
To unregister for push, use the following function:
var optionalOnSuccess = () => {
console.log('unsubscribed to push successfully');
};
var optionalOnFailure = (error) => {
console.log('Failed to unsubscribe to push');
console.error(error);
};
SwrveSDK.unregisterPush(optionalOnSuccess, optionalOnFailure);
In-app messages
Swrve’s in-app message campaigns are available by default and require no additional integration steps. Use in-app messages to send personalized messages to your app users while they’re using your app. For more information, see Intro to in-app messages.
To test in-app messages in your app, you need to first create the campaign in Swrve. For more information, see Creating in-app messages.
In-app message listener
To be notified of in-app message interactions, pass a messageListener function in the inAppMessageConfig config object as part of initialization. This is the Web equivalent of SwrveInAppMessageDelegate on iOS and SwrveInAppMessageListener on Android.
The listener receives callbacks for the following in-app message interactions:
- In-app message impression
- Custom button action
- Dismiss button action
The listener may be called multiple times for the same message, such as for the initial impression and a subsequent button action, so handle each action separately in your callback logic.
Method Signature:
(action, messageDetails, selectedButton) => void
The action argument is one of the following values:
| Value | When it fires |
|---|---|
impression |
The message is displayed, either from a trigger or from showMessageCenterCampaign. |
custom |
The user selects a button configured with a custom action. |
dismiss |
The user selects a dismiss button. |
The messageDetails argument describes the message the interaction belongs to:
| Property | Type | Description |
|---|---|---|
campaignId |
number | ID of the campaign that delivered the message. |
variantId |
number | ID of the message variant. |
messageName |
string | Name of the message as configured in Swrve. |
campaignSubject |
string | Subject of the campaign. Only populated for Message Center campaigns. |
The selectedButton argument describes the button the user selected:
| Property | Type | Description |
|---|---|---|
buttonName |
string | Name of the button as configured in Swrve. |
buttonText |
string | Display text of the button, if the button has text. |
actionType |
string | Action type of the button, for example CUSTOM or DISMISS. |
actionString |
string | Action value of the button, such as the custom action URL. |
selectedButton is undefined for the impression action, because no button is involved. This matches nil on iOS and null on Android.For example:
/** create your message listener */
var messageListenerImp = (action, messageDetails, selectedButton) => {
switch (action) {
case "impression":
/** process impression callback; selectedButton is undefined here */
console.log(`message ${messageDetails.messageName} was shown`);
break;
case "custom":
/** process custom button action callback */
console.log(`custom action: ${selectedButton.actionString}`);
break;
case "dismiss":
/** process dismiss button action callback */
console.log(`dismissed with button ${selectedButton.buttonName}`);
break;
default:
break;
}
};
/** add it to an in-app message config object */
var inAppConfig = {
messageListener: messageListenerImp
};
/** add it to your config on init */
SwrveSDK.initWithConfig({
appId: <app_id>,
apiKey: "<web_api_key>",
externalUserId: "<external_user_id>",
inAppMessageConfig: inAppConfig,
});
If you use TypeScript, @swrve/web-sdk exports the SwrveMessageAction enum along with the ISwrveMessageDetails, ISwrveMessageButtonDetails, and OnSwrveInAppMessageListener types, so you can compare against SwrveMessageAction.Impression, SwrveMessageAction.Custom, and SwrveMessageAction.Dismiss instead of the string values.
messageListener. Use the embeddedCallback in embeddedMessageConfig for embedded campaign content instead.Custom actions and links
When you configure an in-app message button with a custom action, the action value is passed to your listener as selectedButton.actionString, so you can route the user within your web app.
If the custom action starts with http:// or https://, the SDK also opens it in a new browser tab before calling your listener. Custom URL scheme deeplinks, such as myapp://settings, are not opened by the browser and are only passed to your listener.
In-app message text
If required, set the default color of the font, background, and text of your buttons and text boxes, and the color of the area behind the message, via the inAppMessageConfig object as part of initialization. In the absence of these settings, the SDK defaults to a transparent text background, black text color, and the Arial font. Currently, this styling applies to all text that’s displayed.
| Property | Type | Default | Description |
|---|---|---|---|
personalizedTextForegroundColor |
string | #000000 |
Color of the text. Accepts any CSS color value. |
personalizedTextBackgroundColor |
string | transparent |
Background color drawn behind the text. Accepts any CSS color value. |
personalizedTextFontStyle |
string | Arial |
Font family applied to the text. Accepts any CSS font-family value. |
defaultBackgroundColor |
string | rgba(0, 0, 0, 0.8) |
Color of the area behind the message. Accepts any CSS color value. Use a translucent value to keep the page visible behind the message. |
/** create your in-app message config object */
var inAppConfig = {
personalizedTextForegroundColor: "#FF0000",
personalizedTextBackgroundColor: "rgba(0, 0, 0, 0.3)",
personalizedTextFontStyle: "Papyrus, serif",
defaultBackgroundColor: "rgba(0, 128, 0, 0.35)",
};
/** add it to your config on init */
SwrveSDK.initWithConfig({
appId: <app_id>,
apiKey: "<web_api_key>",
externalUserId: "<external_user_id>",
inAppMessageConfig: inAppConfig,
});
Note: These settings are defaults, not overrides. Where a campaign specifies its own font, text color, text background color, or background color in Swrve, the campaign value is used and the configured default only applies where the campaign doesn’t specify one. Custom fonts uploaded with a campaign are also applied ahead of personalizedTextFontStyle. This matches the behavior of the iOS and Android SDKs.
In-app message Stories
The Web SDK renders Story messages using the Story settings configured on the campaign in Swrve, including page duration, timed progression, the segmented progress indicator, and the dismiss button color, size, and position. No additional integration code is required to display Stories.
Note: Unlike the iOS and Android SDKs, the Web SDK does not expose configuration for replacing the Story dismiss button with your own image assets. The dismiss button is rendered from the color and size values assigned to it in the dashboard. Story swipe gestures are also not supported in this release; users progress through Story pages on the configured page timer or by selecting buttons on the page.
Embedded campaigns
Swrve’s embedded campaigns give you complete control over how you deliver, handle, and display content in your web app, while still using Swrve’s audience targeting, event triggering, and goal tracking. Instead of Swrve rendering the UI, the SDK returns JSON to your app and you render it in your own UI components. For more information, see Embedded campaigns.
You can use embedded campaigns in two ways:
- Event-triggered embedded campaigns – the campaign is triggered by an event and delivered through the
embeddedCallback. - Message Center embedded campaigns – the campaign is retrieved from the Message Center and you decide when and where to show it.
Event-triggered embedded campaigns
For event-triggered embedded campaigns, the SDK invokes your embedded callback whenever a matching campaign is triggered. The callback receives the embedded payload and the latest realtime user properties so you can personalize and render the content. Pass the embeddedMessageConfig config object with your callback before initializing the SDK:
/** create your embedded callback */
var embeddedCallbackImp = (message, personalizationProperties, isControl) => {
if (isControl) {
/** This campaign should not be shown to the user. Send an impression event for reporting. */
SwrveSDK.embeddedControlMessageImpressionEvent(message);
return;
}
/** Personalize the embedded JSON for this user */
var personalizedData = SwrveSDK.getPersonalizedEmbeddedMessageData(
message,
personalizationProperties
);
if (!personalizedData) {
return;
}
/** When you actually show the content, record the impression */
SwrveSDK.embeddedMessageWasShownToUser(message);
};
/** add it to an embedded config object */
var embeddedConfig = { embeddedCallback: embeddedCallbackImp };
/** add it to your config on init */
SwrveSDK.initWithConfig({
appId: <app_id>,
apiKey: "<web_api_key>",
externalUserId: "<external_user_id>",
embeddedMessageConfig: embeddedConfig,
});
The isControl argument is true when the campaign is configured as a control campaign to measure the impact of showing no message. A control campaign has no content to display, so report the control impression and return without rendering.
Trigger your embedded campaigns with normal events:
/** Example: trigger an embedded banner campaign */
SwrveSDK.event("banner");
If your embedded content has interactive elements, for example a CTA button, send click events when the user interacts with them. The message.buttons property is a list of strings representing the button options configured in Swrve:
/** Called when the user selects a CTA in your custom UI */
function onEmbeddedCtaClicked(message, buttonName) {
SwrveSDK.embeddedMessageButtonWasPressed(message, buttonName);
}
This lets you use Swrve’s tracking, holdout groups, and personalization while retaining full control over how the embedded content looks and behaves.
Message Center embedded campaigns
Message Center embedded campaigns are not delivered via the embedded callback. Instead, you fetch them with getEmbeddedMessageCenterCampaigns and decide where and when to render them, for example a carousel on your home page. You can optionally pass personalization properties to resolve the campaign content.
Method signature:
static getEmbeddedMessageCenterCampaigns(
personalizationProperties?: IDictionary<string>
): ISwrveEmbeddedMessage[];
To retrieve Message Center embedded campaigns for a carousel:
function loadEmbeddedFromMessageCenter() {
/** Returns all eligible embedded Message Center campaigns for the current user */
var embeddedMessages = SwrveSDK.getEmbeddedMessageCenterCampaigns({
user_name: "Sam"
});
/** Optionally filter by type or other metadata in your JSON payload,
* for example: type == "carousel"
*/
return embeddedMessages.filter((message) => {
/** Must be JSON embedded data */
if (message.type !== "json") {
return false;
}
try {
var payload = JSON.parse(message.data);
return String(payload.type).toLowerCase() === "carousel";
} catch (e) {
return false;
}
});
}
You then parse the embedded payload and render it in your carousel UI:
/** pseudo code */
function parseCarouselItem(message) {
/** Only JSON embedded messages are expected to contain this payload */
if (message.type !== "json") {
return null;
}
var payload;
try {
payload = JSON.parse(message.data);
} catch (e) {
return null;
}
/** type must be "carousel" */
if (String(payload.type).toLowerCase() !== "carousel") {
return null;
}
return {
title: payload.title,
body: payload.body,
imageUrl: payload.image,
};
}
When a carousel card is actually visible to the user, record an impression. When the user interacts with it, for example selects a card or a CTA, record a click:
/** Called when a specific carousel item becomes visible */
function onCarouselItemShown(message) {
SwrveSDK.embeddedMessageWasShownToUser(message);
}
/** Called when the user selects a carousel CTA */
function onCarouselCtaClicked(message, buttonName) {
SwrveSDK.embeddedMessageButtonWasPressed(message, buttonName);
}
Embedded campaign personalization
Swrve provides built-in personalization support for embedded campaigns. Personalization in any kind of triggered campaign uses a set of custom properties you’ve implemented in your app and then configured for realtime personalization in Swrve. For information about configuring these properties, see Manage user properties or contact your CSM at support@messagegears.com. Once configured, the properties are immediately available for use in your embedded campaigns.
The Swrve SDK has direct access to the most recent version of the realtime user property values in Swrve. When your app makes an embedded campaign callback, the contents of the personalizationProperties argument in the embedded message include the realtime user properties retrieved during the process of triggering the campaign.
Since the format of embedded campaigns depends on how you configured your app (for example, you might use JSON, XML, or plain text), Swrve does not parse and process your embedded campaign content. Although the campaign editor lets you select realtime properties for personalization, it is your responsibility to inject the properties as part of your embedded campaign integration. To help make this process easier, Swrve provides the getPersonalizedEmbeddedMessageData API.
var embeddedCallbackImp = (message, personalizationProperties) => {
var resolvedMessageData = SwrveSDK.getPersonalizedEmbeddedMessageData(
message,
personalizationProperties
);
};
Message Center campaigns
Campaigns that have the Message Center flag set in Swrve are not shown automatically. Instead, your app retrieves them and controls when and where they appear, so the user is in control of the message lifecycle.
The Web SDK supports the full Message Center API, including getMessageCenterCampaigns, getInAppMessageCenterCampaigns, getEmbeddedMessageCenterCampaigns, getMessageCenterCampaign, showMessageCenterCampaign, markMessageCenterCampaignAsSeen, and removeMessageCenterCampaign.
For the available campaign properties, the campaign lifecycle, and code examples for each call, see Swrve Message Center API.
Sending events
The Swrve SDK automatically sends certain events and also enables you to track user behavior by sending custom events. (For a list of default Swrve events, see About segment and audience filters, Events.) In turn, you can use app-generated events to trigger in-app messages on other platforms, while both app- and server-generated events help you define segments and perform in-depth analysis.
Custom events
To send a custom event, include the below example in a method where you want to send an event to Swrve.
Method Signature:
static event(name: string): void;
SwrveSDK.event("custom.event_name");
Requirements for sending custom events:
- Do not send the same named event with different case. For example, if you send tutorial.start, then ensure you never send Tutorial.Start.
- Use a period (.) in your event names to organize their layout in the Swrve dashboard. Each ‘.’ creates a new branch in the Event name column of the Events report, and groups your events so they are easy to locate.
- Do not send more than 1000 unique named events.
- Do not add unique identifiers to event names. For example, Registration.Start.ServerID-ABDCEFG
- Do not add timestamps to event names. For example, Registration.Start.1454458885
- Do not use the swrve.* or Swrve.* namespace for your own events. This is reserved for Swrve use only. Custom event names beginning with Swrve. are restricted and cannot be sent.
Event payloads
You can add and send an event payload with every event. This allows for more detailed reporting around events and funnels.
Method Signature:
static event(name: string, payload?: IDictionary): void;
Notes on associated payloads:
- The associated payload should be a dictionary of key/value pairs; it is restricted to string and integer keys and values.
- There is a maximum cardinality of 500 key-value pairs for this payload per event. This parameter is optional, but only the first 500 payloads are displayed in the dashboard. The data is still available in raw event logs.
- If you want to use event payloads to target your campaign audiences, you can configure up to 10 custom events with a maximum of 20 payloads per event for audience filtering purposes. For more information, see Targeting your audience by event payloads.
SwrveSDK.event("custom.event_name", {key1: "value1", key2: "value2"});
For example, if you want to track when a user starts the registration experience, it might make sense to send an event named registration.start and add a payload time that captures how much time it took the user to complete the registration.
SwrveSDK.event("registration.start", { time: "100", step: 5});
Custom user properties
The Swrve SDK sends certain user properties by default and also enables you to assign custom properties to update the user’s status. (For a full list of the default user properties, see Assigning user properties.)
For example, you could create a custom user property called premium, and then target non-premium users and premium users in your campaigns.
When configuring custom properties, the Swrve SDK only supports string values.
Method Signature:
static userUpdate(attributes: IReadonlyDictionary): void;
Example of group of user properties
SwrveSDK.userUpdate({ premium: "true", level: "12", balance: "999"});
Example of date-typed user property
Method Signature:
static userUpdateWithDate(keyName: string, date: Date): void;
Use the Date object to send a DateTime user property; for example, the current date at the time of a user purchase:
SwrveSDK.userUpdateWithDate("last_purchase", new Date());
Virtual economy events
To ensure virtual currency events are not ignored by the server, make sure the currency name configured in your app matches exactly the Currency Name you enter in the App Currencies section on the App Settings screen (including case-sensitive). If there is any difference, or if you haven’t added the currency in Swrve, the server will ignore the event and return an error event called Swrve.error.invalid_currency. Additionally, the ignored events are not included in your KPI reports. For more information, see Add your app.
If your app has a virtual economy, send the purchase event when users purchase in-app items with virtual currency.
Method Signature:
static purchase(name: string, currency: string, cost: number, quantity: number): void;
SwrveSDK.purchase("some.item", "gold", 99, 1)
In-app purchase events
To notify Swrve of an in-app purchase, use the function below. For Web, Swrve does not currently validate in-app purchases. If you want to build revenue reports for your app, you must validate the receipt on your side before sending it to Swrve. For more information on the arguments passed through, see the Swrve Events API.
Method Signature:
static iap(quantity: number, productId: string, productPrice: number, currency: string, rewards?: IReadonlyDictionary): void;
Example
var rewards = {}
rewards["Gold"] = { type: "currency", amount: 200 };
rewards["Item"] = { type: "item", amount: 100 };
SwrveSDK.iap(1,"item_purchased", 100, "euro", rewards)
Resource A/B testing
Integrating Swrve’s resource A/B testing functionality enables you to use Swrve to test how users respond to changes to the native app content. For more information about resource A/B testing, see Intro to resource A/B testing.
To get the latest version of a resource from Swrve using the Resource Manager, use the following:
var resourceManager = SwrveSDK.resourceManager()
var welcomeString = resourceManager.getAttributeAsString("new_app_config", "welcome_text", "Welcome!");
Or you can use the Swrve Resource instance API:
var resource = SwrveSDK.resourceManager().getResource("my.screen");
var welcomeString = resource.getAttributeAsString("welcome_text", "Welcome!");
var textSize = resource.getAttributeAsNumber("text_size", 14);
If you want to be notified whenever resources change, you can add a callback function as follows:
SwrveSDK.onResourcesLoaded = (resources) => {
// Callback functionality
};
Testing your integration
After you’ve completed the above, the next step is to test the integration. For more information, see Testing your integration.
Upgrade instructions
If you’re moving from an earlier version of the Web SDK to the current version, see the Web SDK upgrade guide for upgrade instructions.