Website SDK Reference

Website SDK Javascript Reference

Initialization
initInitializes the Web SDK.
pushGives access to the rest of the SDK API asynchronously, when it is loaded and ready to use.
Subscribing users
subscribeToNotificationsPrompts user to subscribe to web push notifications.
unsubscribeFromNotificationsUnsubscribes user from web push notifications.
isSubscribedToNotificationsTells whether user is subscribed to web push notifications.
sendSelfNotificationSends a notification back to the user, for testing, or with a given message.
setUserIdAssigns the provided user ID to the user. When the user ID changes, a new installation is created.
getUserIdReturns a Promise that resolves to a string equal to the user ID or null.
User Interfaces
showSubscriptionDialogShows a system-like dialog box at the top of the screen prompting users to subscribe to push notifications.
showSubscriptionBellShows a small widget at the lower-left corner of the screen that prompts users to subscribe to push notifications when clicked.
showSubscriptionSwitchShows a switch-like widget inside the specified container DOM element that allows users to subscribe and unsubscribe from push notifications.
showTagSwitchesShows a collection of switch-like widgets inside the specified container DOM element that allows users to subscribe and unsubscribe from push notifications, and tag themselves at the same time.
Segmentation
trackEventSends an event with a name and payload of your choice.
addTagAdds one or more tags to this installation.
removeTagRemoves one or more tags from this installation.
removeAllTagsRemoves all tags from this installation.
hasTagTests whether a given tag is attached to this installation.
getTagsReturns all the tags attached of this installation.
getPropertyValueReturns the value of a given property associated to this installation.
getPropertyValuesReturns an immutable list of the values of a given property associated to this installation.
addPropertyAdds the value to a given property associated to this installation.
removePropertyRemoves the value from a given property associated to this installation.
setPropertySets the value to a given property associated to this installation.
unsetPropertyRemoves the value of a given property associated to this installation.
putPropertiesAssociates the provided name/value pairs to this installation.
getPropertiesReturns all the name/value pairs associated to this installation using putProperties.
useGeolocationEnables or disables the collection of the geolocation position.
Privacy
setUserConsentProvides privacy consent.
clearEventsHistoryClears all events recorded using trackEvent.
clearPreferencesClears all the name/value pairs associated to this installation using putProperties.
clearAllData
downloadAllDataInitiates the download of all the WonderPush data related to the current installation, in JSON format.
Custom DOM Events
subscriptionA custom DOM event fired on the window object when the user subscribes or unsubscribes.
In-app messaging
setInAppMessagingDisplayCallbackLets you handle the display of in-apps yourself.
setInAppMessagesSuppressedLets you disable or enable in-app messaging.
getInAppMessagesSuppressedWhether in-app messaging is disabled.

Initialization

Loading SDK Asynchronously

WonderPush recommends loading wonderpush-loader.min.js with the async flag so your page load times don't increase. To use it, place the following code before calling any other WonderPush functions.

<script src="https://cdn.by.wonderpush.com/sdk/1.1/wonderpush-loader.min.js" async></script>
<script>window.WonderPush = window.WonderPush || [];</script>

Our API functions can be called asynchronously using either:

  1. WonderPush.push(["functionName", param1, param2]);
  2. WonderPush.push(function() { WonderPush.functionName(param1, param2); });

See push for more details.

init

Call this function from every page of your site to initialize WonderPush. This call is required before any other function can be used. You must use push with the array syntax to call init.

WonderPush.push(["init", {
  webKey: "YOUR_WEBKEY",
  // other initialization options 
}]);
ParameterTypeDescription
optionsObjectInitialization options described below

Initialization options are:

OptionTypeDescription
webKeyStringRequired The web key of your project. Find it your dashboard under the Settings / Configuration page, in the Website tab.
userId StringThe unique identifier of the user in your systems. Provide this on every page when the user is logged in.
applicationNameStringThe name of your website. Defaults to the value you've chosen in your dashboard, or your website hostname. Displayed during the registration process.
applicationVersionStringThe version of your website. Can be used for Segmentation.
geolocation"auto" or BooleanReport the geolocation of this installation. Possible values are:
- "auto" (default): watch and report the geolocation of this installation if the permission is already granted, but never prompt for the GeoLocation permission.
- true: prompt the user at page load if necessary, watch and report the geolocation of this installation if the permission is granted.
- false: do not report geolocation.

Use "auto" and call WonderPush.useGeolocation(true) if you wish to prompt users at a more appropriate time than page load.
notificationIconStringThe absolute URL to the notification icon. Prefer https when possible. Displayed in the registration process and push notifications.

Defaults to the icon uploaded in your dashboard.
notificationDefaultUrlStringThe default URL that will be opened when users click on notifications.

Defaults to the value chosen in your dashboard. Usually set to the homepage of your website.
requiresUserConsentBooleanDelay the initialization of the SDK until setUserConsent is called. Defaults to false. Set this totrue for GDPR compliance.
allowedSubscriptionDomainsArray | undefinedPass an array of external domains you wish to allow subscription from. Pass an empty array to disallow cross-domain subscription altogether. Pass undefined to allow subscription from any domain. The notification domain configured in your dashboard is always allowed.
subscriptionDialogObjectSee Subscription Dialog Options.
subscriptionBellObjectSee Subscription Bell Options.
subscriptionSwitchObjectSee Subscription Switch Options.
subscriptionNativeObjectSee Native Subscription Options
optInOptionsObjectSee Cross-domain Options

push

Pass in a callback and it will be executed when WonderPush is ready to operate. Pass in an array starting with a string and the corresponding function will be called.

WonderPush is ready to use when the async script tag has been loaded,
and its configuration fetched.

If you've specified requiresUserConsent: true in your init, WonderPush will also wait for setUserConsent to be called with true.

Callback syntax

This syntax is the most convenient to call multiple WonderPush functions in a single block, and to read their return values.

Please note that this syntax can not be used for functions available prior to initialization such as init and setUserConsent.

WonderPush.push(function() {
  // Do something with the WonderPush object.
})

Array syntax

This syntax is more compact when you don't need to read the result of the function. It is also the only option when calling functions available prior to initialization such as init and setUserConsent.

// call some function on the WonderPush object when ready
WonderPush.push(["someFunction", param1, param2]);

Previous SDKs ready

In previous versions of our SDK, push used to be called ready. If you're using the deprecated ready, your app will continue to work.
You should consider upgrading by following the migration instructions.

Subscribing users

subscribeToNotifications

Subscribes to push notifications.

If you're calling this function from a domain or subdomain that is not the push notification domain as specified in your dashboard, or if you're calling this function from a non-HTTPS page, the registration process must open a pop-up window. To avoid pop-up blockers, specify the event related to the user click as first argument of the subscribeToNotifications function.

ParameterTypeDescription
eventEventRECOMMENDED. If you call this function in response to a user event, give that event here.
<a href="#" onclick="WonderPush.subscribeToNotifications(event); return false;">Subscribe to push notifications</a>

In this example we create a link that triggers the push notification subscription process.

unsubscribeFromNotifications

Unsubscribes from push notifications.

Please note that calling this function does not affect the push notification permission.

<a href="#" onclick="WonderPush.unsubscribeFromNotifications(); return false;">Unsubscribe from push notifications</a>

isSubscribedToNotifications

Returns a Promise object that resolves to a boolean indicating whether the user is subscribed to push notifications.

window.WonderPush = window.WonderPush || [];
WonderPush.push(function() {
  WonderPush.isSubscribedToNotifications().then(function (isSubscribed) {
    console.log("is user subscribed to notifications: ", isSubscribed);
  });
});

In this example, we wait for WonderPush to be ready with the push function, then we call isSubscribedToNotifications and log the result to the console once the Promise resolves.

sendSelfNotification

Request the WonderPush servers to send a notification back to the calling user.
If called with no argument, a default testing message is used.

ParameterTypeDescription
optionsObjectOptional options for controlling which message to send back to the calling user.

This method works like a stripped down version of the POST /v1/deliveries endpoint of the Management API.
The allowed options, all optional, are:

OptionTypeDescription
campaignIdStringThe campaign identifier of the notification to trigger.

If notification is not given, the notification composed inside that campaign will be used.
Otherwise, the given notification is used, but the statistics will still be attached to the given campaign.
notificationIdStringThe notification identifier within the given campaign. Used to choose among multiple A/B variants.
notificationObject
See The Notification object for more information on accepted values.
The notification to deliver. If campaignId is given, this parameter is optional.

If given, this parameter will replace the notification composed in the campaign.
If you want to control which message to send from the client side, then this is the parameter you are looking for.
notificationOverrideObject
See The Notification object for more information on accepted values.
Applies partial modifications to the notification taken from the campaign.

This contrasts from the notification parameter that replaces the notification altogether.
notificationParamsObject or array of a single objectFills any notification parameter with the given values.

If using the array syntax, it must hold a single object as value.

Typical usage includes:

  • Testing proper configuration, when called with no parameter.
  • Manually triggering a notification directly from the user's device, using texts generated from the website itself, when using the notification option.
  • Manually triggering a notification directly from the user's device, using texts entered in the dashboard, when using the campaignId option.
  • Manually triggering a notification directly from the user's device, using texts entered in the dashboard, while filling some parameters from the website itself, when using the campaignId and notificationParams options.

setUserId

Sets the user ID to the provided value. When the user ID changes, a new installation is created. See User IDs for more on using your own user IDs.

window.WonderPush = window.WonderPush || [];
WonderPush.push(['setUserId', "ADAPT_THIS_USER_ID"]);

getUserId

Returns a Promise resolving to the current user ID or null.

window.WonderPush = window.WonderPush || [];
WonderPush.push(function() {
  WonderPush.getUserId().then(console.log);
});

Native Subscription Options

These initialization options can be passed to init under the subscriptionNative field, to trigger the native subscription dialog of your web browser.

OptionTypeDescription
triggersObjectOptions to automatically show the native subscription dialog. See Trigger Options.

User Interfaces

showSubscriptionDialog

Show the subscription dialog as configured by the subscriptionDialog init options.

The subscription dialog is shown from the top of the window and looks like this:

Subscription Dialog Options

These initialization options must be placed within your call to init, inside the subscriptionDialog field.

OptionTypeDescription
triggersObjectOptions to automatically show the subscription dialog. See Trigger Options.
titleStringTitle of the dialog. Defaults “Would you like to subscribe to push notifications?”
messageStringMessage displayed in the dialog. Defaults to “You can always unsubscribe at any time.”.
positiveButtonStringLabel of the button that triggers the subscription process. Defaults to “Subscribe”.
negativeButtonStringLabel of the button that closes the dialog. Defaults to “Later”.
styleObjectAn object containing CSS properties, applied to the dialog top level element style property. Use camel-case property names. For example: { backgroundColor: 'white' }.
You can also add any CSS rules in your pages targeting the wp-optin-dialog-* classes. Use your browser inspector to experiment and guide you.
positiveButtonBackgroundColorStringThe hex color code of the positive button.
negativeButtonBackgroundColorStringThe hex color code of the negative button.
positiveButtonTextColorStringThe hex color code of the positive button.
negativeButtonTextColorStringThe hex color code of the negative button.
backgroundColorStringThe hex color code of the dialog background.
textColorStringThe hex color code of the dialog text.
iconStringURL to the icon file. Prefer https. Defaults to the icon configured in your dashboard.
hidePoweredByBooleanHides the “Powered by WonderPush” mention. Defaults to false.
closeSnoozeNumber or BooleanHow long to force to wait before presenting the dialog again, if the user clicks the close button.
Use a duration in milliseconds, false to not set any extra snooze, true to never present again.
Defaults to false, which relies on the SDK's default trigger snooze of 12 hours, without forcing extra snooze.
negativeSnoozeNumber or BooleanHow long to force to wait before presenting the dialog again, if the user clicks the negative button.
Use a duration in milliseconds, false to not set any extra snooze, true to never present again.
Defaults to 604800, 7 days.

For examplem this corresponds to the default options:

WonderPush.push(["init", {
  // ... other options
  subscriptionDialog: {
    triggers: {},
    title: "Would you like to subscribe to push notifications?",
    message: "You can always unsubscribe at any time.",
    positiveButton: "Subscribe",
    negativeButton: "Later",
  },
}]);

Trigger Options

Trigger options are used to trigger behaviors based on the navigation of the user. Trigger options can be combined to create complex behaviors.

For example:

WonderPush.push(["init", {
  // ... other options
  subscriptionDialog: {
    triggers: {
      minPages: 3,
      snooze: 86400000, // 24 hours
    }
  },
}]);

In this example, the subscription dialog automatically appears after 3 page views. If the user closes or dismiss the dialog, the dialog will appear again after the user performed 3 more page views and 24 hours have elapsed.

Trigger options are:

OptionTypeDescription
minVisitsNumberHow many visits should the user have performed before triggering automatic behavior.
minPagesNumberHow many pages should the user have viewed before triggering automatic behavior.
minVisitPagesNumberHow many pages should the user have viewed within its current visit before triggering automatic behavior.
delayNumberHow much time (in milliseconds) should the automatic behavior be delayed from page load.
snoozeNumberHow long to wait before automatically triggering the behavior again, in milliseconds. Defaults to 43200000 (12 hours). For example, a value of 3600000 ensures the dialog doesn't appear more than once every hour.
manualBooleanSetting this value to true completely disables the automatic behavior. Use in conjunction with showSubscriptionDialog to show the dialog at a time of your choosing. Defaults to false.

showSubscriptionBell

Show or hide the subscription bell as configured by the subscriptionBell init options. The subscription bell sits at the bottom left or right corner of the window and can be used to give users a permanent access to subscribe to notifications, unsubscribe, and manage their private data

The subscription bell looks like this:

ParameterTypeDescription
showBooleanWhether to show the subscription bell.
window.WonderPush = window.WonderPush || [];
WonderPush.push(function() {
  // Hide the subscription bell
  WonderPush.showSubscriptionBell(false);
});
<!-- A button that shows the subscription bell -->
<a href="#" 
   onclick="WonderPush.showSubscriptionBell(true); return false;"
   >Show subscription bell</a>

Subscription Bell Options

These initialization options must be specified within your call to init, inside the subscriptionBell field.

OptionTypeDescription
hideWhenSubscribedBooleanHide the bell when the user is subscribed. Defaults to false.
styleObjectAn object containing CSS properties, applied to the dialog top level element style property. Use camel-case property names. For example: { backgroundColor: "white" }.
cssPrefixStringA prefix to be used in front of all CSS classes. Use this to reset our styles and put your own. Defaults to "wonderpush-".
colorStringMain color of the widget. Defaults to "#ff6f61".
positionStringAcceptable values are "left" or "right". Defaults to "left".
bellIconStringURL of the bell icon. Prefer https.
dialogTitleStringTitle of the settings dialog. Defaults to "Manage Notifications".
subscribeButtonTitleStringTitle of the subscribe button. Defaults to "Subscribe".
unsubscribeButtonTitleStringTitle of the subscribe button. Defaults to "Unsubscribe".
notificationIconStringUrl of the mock notification icon in the settings dialog. Defaults to your app's notification icon as specified in your dashboard. Using https:// is strongly recommended.
subscribeInviteTextStringText displayed to invite user to subscribe. Defaults to "Click to subscribe to notifications".
alreadySubscribedTextStringText displayed when already subscribed users hover the notification bell. Defaults to "You're subscribed to notifications".
alreadyUnsubscribedTextStringText displayed when unsubscribed users hover the notification bell. Defaults to "You are not receiving any notifications".
blockedTextStringText displayed when already users have blocked notifications. Defaults to "You've blocked notifications".
subscribedTextStringText displayed when users subscribe. Defaults to "Thanks for subscribing!".
unsubscribedTextStringText displayed when users unsubscribe. Defaults to "You won't receive more notifications".
advancedSettingsDescriptionStringText displayed above advanced settings. Defaults to "Your personal notification data:".
advancedSettingsFineprintStringText displayed below advanced settings. Defaults to "WonderPush fully supports european GDPR".
downloadDataButtonTitleStringTitle of the download button. Defaults to "Download".
clearDataButtonTitleStringTitle of the clear button. Defaults to "Clear".
hidePrivacySettingsBooleanBy default, subscribed users see a Settings button giving them access to privacy settings. When hidePrivacySettings is specified, the settings button is hidden. Defaults to false.
showBadgeBooleanWhen true, a badge with an unread count of "1" will be displayed the first time users see the bell. Defaults to true.

showSubscriptionSwitch

Appends a subscription switch dynamically to the provided parentNode, typically used for Single Page Applications.

WonderPush = window.WonderPush || [];
WonderPush.push(function() {
    var parentNode = document.getElementById('theIdOfSomeElementYouWantToAddASwitchTo');
    WonderPush.showSubscriptionSwitch(parentNode);
});

The subscription switch allows users to subscribe to notifications and unsubscribe.

An alternative to using showSubscriptionSwitch is to create an element with id wonderpush-subscription-switch. At page load time, WonderPush will turn this element into a subscription switch. Most of the options below can be specified directly on the wonderpush-subscription-switch element itself via data- attributes:

<div id="wonderpush-subscription-switch"
        data-sentence="Subscribe to notifications: "></div>

The subscription switch looks like this:

ParameterTypeDescription
parentNodeHTMLElementThe node where we'll put the subscription switch using appendChild.
optionsObjectCustomize the appearance of the subscription switch. See subscriptionSwitch init options.

Subscription Switch Options

Most of these initialization options can be specified within your call to init inside the subscriptionSwitch field, or directly in your call to showSubscriptionSwitch, to the exception of switchElementId that can only be specified at init time.

OptionTypeDescription
switchElementIdStringThe id of the placeholder element this the SDK will use to flesh out a subscription switch. Defaults to wonderpush-subscription-switch. This option cannot be overridden from the placeholder element.
classPrefixStringThe prefix to prepend to all the CSS classes names used. Defaults to wp-.
prependStringOptional HTML code to inject before the actual switch element.
appendStringOptional HTML code to inject after the actual switch element.
sentenceStringHTML snippet to inject in a SPAN tag right before the switch.
cssClassStringCSS class to add to the switch element.
onStringLabel of the switch in the ON state.
offStringLabel of the switch in the OFF state.
colorOnStringName of a predefined color to use for the ON state. Valid values are blue and green. Defaults to blue.
colorOffStringName of a predefined color to use for the OFF state. Valid values are gray, grey or red. Defaults to gray.

showTagSwitches

Appends a collection of tag switches to the provided parentNode.

The tag switches allow users to subscribe to notifications and tag themselves at the same time. You can use tag switches to let users subscribe to topics of their choice for example.

An alternative to using showTagSwitches is to create an element with class wonderpush-tag-switch. At page load time, WonderPush will turn this element into a tag switch. Most of the options below can be specified directly on the wonderpush-tag-switch element itself via data- attributes:

<script>
  window.WonderPush = window.WonderPush || [];
    WonderPush.push(function() {
    WonderPush.showTagSwitches(document.body, [
      {sentence: 'Sports: ', tag: 'sports'},
    ]);
  });
</script>

Would be equivalent to:

<div class="wonderpush-tag-switch"
     data-sentence="Sports: "
     data-tag="sports"></div>

And would render something like this:

ParameterTypeDescription
parentNodeHTMLElementThe node where we'll put the tag switches using appendChild.
optionsArraySpecify the switches. See tagSwitch options.

Tag Switch Options

* Either the tag or the field together with value options are mandatory. They define what tag is manipulated, or what value is to be put or removed and into which property field, when the switch is flipped.

OptionTypeDescription
tagStringThe name of the tag to manipulate. Either this option or both field and value must be given.
fieldStringThe name of the property to manipulate. Either this option along with value, or tag must be given,
valueStringThe value to manipulate in the field-named property. Either this option along with field, or tag must be given,
classPrefixStringThe prefix to prepend to all the CSS classes names used. Defaults to wp-tag-.
prependStringOptional HTML code to inject before the actual switch element.
appendStringOptional HTML code to inject after the actual switch element.
sentenceStringHTML snippet to inject in a SPAN tag right before the switch.
cssClassStringCSS class to add to the switch element.
onStringLabel of the switch in the ON state.
offStringLabel of the switch in the OFF state.
colorOnStringName of a predefined color to use for the ON state. Valid values are blue and green. Defaults to blue.
colorOffStringName of a predefined color to use for the OFF state. Valid values are gray, grey or red. Defaults to gray.

Cross-domain popup window

When subscribing users from another domain than the one configured in your dashboard, a pop-up window will appear. This process is called cross-domain subscription.

Elements of this popup window are configurable via the Cross-domain options below.

Cross-domain Options

These options control the texts displayed by the cross-domain popup window.

OptionTypeDescription
externalBoxMessageStringThe main message below your website name. Defaults to “We'd like to send you notifications”.
externalBoxExampleTitleStringThe title of the example notification. Defaults to “Example notification”.
externalBoxExampleMessageStringThe message of the example notification. Defaults to “This is an example notification”.
externalBoxDisclaimerStringThe fineprint displayed below the example notification. Defaults to “You can always unsubscribe at anytime.”.
externalBoxProcessingMessageStringThe message written when user accepts and subscription is in progress. Defaults to “Subscribing...”.
externalBoxSuccessMessageStringThe message displayed when subscription is successful. Defaults to “Thanks for subscribing!”.
externalBoxFailureMessageStringThe default error message when subscription fails. Defaults to “Sorry, something went wrong.”.
externalBoxTooLongHintStringThe error message displayed when subscribing takes too long. Defaults to “Poor connection or private browsing?”.
positiveButtonTextStringThe text of the subscription button (shown on Firefox only)
negativeButtonTextStringThe text of the cancel button (shown on Firefox only)

For example, this corresponds to the default values:

WonderPush.push(["init", {
  // ... other options
  optInOptions: {
    externalBoxMessage: "We'd like to send you notifications",
    externalBoxExampleTitle: "Example notification",
    externalBoxExampleMessage: "This is an example notification",
    externalBoxDisclaimer: "You can always unsubscribe at anytime.",
    externalBoxProcessingMessage: "Subscribing...",
    externalBoxSuccessMessage: "Thanks for subscribing!",
    externalBoxFailureMessage: "Sorry, something went wrong.",
    externalBoxTooLongHint: "Poor connection or private browsing?",
    externalBoxCloseHint: "Close",
    positiveButtonText: "Subscribe",
    negativeButtonText: "Later",
    },
}]);

Segmentation

Segmentation functions allow you to mark installations so they can be added to segments and you can send them targeted notifications later.

There are many ways of performing segmentation:

Tags are like labels you can stick on users. Use tags to create segments in your dashboard and send targeted push notifications. Example: all users that have the "customer" tag.

Events have a date, a type of your choice and attributes. Use events to create segments in your dashboard and send targeted push notifications. Example: all users that purchased in the last hour is a typical event-based segment.

Installation properties represent traits of the user. That's a good place to store age, gender and other data traditionally used for segmentation. Create property-based segments in your dashboard. Example: all users above 18 is a typical property-based segment.

trackEvent

Tracks a custom event of your choice. E.g. purchase.

ParameterTypeDescription
typeStringRequired The type of the event to track. Event names starting with @ are reserved for internal use and cannot be used here.
attributesObjectAttributes associated with this event. See format of property names for detailed syntax.

Example:

WonderPush.push(function() {

  WonderPush.trackEvent('purchase', {
    string_product: "Some product",
    float_price: 1.99,
  });

});

addTag

Adds one or more tags to the current installation.

WonderPush.push(function() {

  WonderPush.addTag("customer");
  WonderPush.addTag("economics", "sport", "politics");

});

removeTag

Removes one or more tags from the current installation.

WonderPush.push(function() {

  WonderPush.removeTag("customer");
  WonderPush.removeTag("economics", "sport", "politics");

});

removeAllTags

Removes all tags from the current installation.

hasTag

Tests whether a given tag is attached to the current installation.

WonderPush.push(function() {

  WonderPush.hasTag("customer").then(function(isCustomer) {
    if (isCustomer) {
      // Display paid features
    }
  });

});

getTags

Returns all the tags attached to the current installation as a promise resolving to an array of strings.

WonderPush.push(function() {

  WonderPush.getTags().then(function(tags) {
    // Work on the tags variable
  });

});

getPropertyValue

Returns a Promise that resolves to the value of a given property associated to the current installation.

If the property stores an array, only the first value is returned. This way you don't have to deal with potential arrays if that property is not supposed to hold one. Returns null if the property is absent or has an empty array value.

ParameterTypeDescription
fieldStringThe name of the property to read values from.
WonderPush.push(function() {

  WonderPush.getPropertyValue("string_lastname").then(function(lastName) {
    // Use lastName
  });

});

getPropertyValues

Returns a Promise that resolves to an array of the values of a given property associated to the current installation.

If the property does not store an array, an array is returned nevertheless. This way you don't have to deal with potential scalar values if that property is supposed to hold an array. Returns an empty array instead of null if the property is absent. Returns an array wrapping any scalar value held by the property.

ParameterTypeDescription
fieldStringThe name of the property to read values from.
WonderPush.push(function() {

  WonderPush.getPropertyValues("string_favorityPlayers").then(function(favoritePlayers) {
    // Use the favoritePlayers array
  });

});

addProperty

Adds the value to a given property associated to the current installation.

The stored value is made an array if not already one. If the given value is an array, all its values are added. If a value is already present in the stored value, it won't be added.

ParameterTypeDescription
fieldStringThe name of the property to add values to.
See format of property names for detailed syntax.
valueany, any[], any...The value(s) to be added. Can be an array, or multiple arguments.
WonderPush.push(function() {
  
  // You can add a single value
  WonderPush.addProperty("string_interests", "sport");
  
  // You can add multiple values
  WonderPush.addProperty("string_interests", "sport", "entertainment");
  
  // You can add an array of values
  WonderPush.addProperty("string_interests", ["sport", "entertainment"]);
  
});

removeProperty

Removes the value from a given property associated to the current installation.

The stored value is made an array if not already one. If the given value is an array, all its values are removed. If a value is present multiple times in the stored value, they will all be removed.

ParameterTypeDescription
fieldStringThe name of the property to remove values from.
valueany, any[], any...The value(s) to be removed. Can be an array, or multiple arguments.
WonderPush.push(function() {
  
  // You can remove a single value
  WonderPush.removeProperty("string_interests", "sport");
  
  // You can remove multiple values
  WonderPush.removeProperty("string_interests", "sport", "entertainment");
  
  // You can remove an array of values
  WonderPush.removeProperty("string_interests", ["sport", "entertainment"]);
  
});

setProperty

Sets the value to a given property associated to the current installation.

The previous value is replaced entirely. Setting undefined or null has the same effect as unsetProperty.

ParameterTypeDescription
fieldStringThe name of the property to set.
See format of property names for detailed syntax.
valueany, any[]The value to be set. Can be an array.
WonderPush.push(function() {
  
  // You can set a single value
  WonderPush.setProperty("bool_isCustomer", true);
  
  // You can remove a field using null or undefined
  WonderPush.setProperty("int_age", null);
  
  // You can set an array of values
  WonderPush.setProperty("string_interests", ["sport", "entertainment"]);
  
});

unsetProperty

Removes the value of a given property associated to the current installation.

The previous value is replaced with null.

ParameterTypeDescription
fieldStringThe name of the property to unset.
WonderPush.push(function() {
  
  WonderPush.unsetProperty("string_favoritePlayers");
  
});

putProperties

Updates the properties of the current installation. Omitting a previously set property leaves it untouched. To remove a property, you must pass it explicitly with a value of null.

ParameterTypeDescription
propertiesObjectProperties to add or update. See format of property names for detailed syntax.

Example:

WonderPush.push(function() {

  // Puts the int_age property with a value of 34 in the installation
  WonderPush.putProperties({
    int_age: 34
  });
});

getProperties

Returns a Promise that resolves to an Object containing the properties of the current installation.

Example:

WonderPush.push(function() {

  WonderPush.getProperties().then(function(properties) {
    console.log("Properties of the current installation are:", properties);
  });
});

useGeolocation

Attach GeoLocation position to this installation.

ParameterTypeDescription
enable"auto" or BooleanPossible values are:
- "auto": watch and report position to this installation if the permission is already granted, but never prompt for the GeoLocation permission.
- true: prompt the user at page load if necessary, watch and report position to the installation if the permission is granted.
- false (default): do not collect or report GeoLocation position.

See the geolocation initialization option to prompt users at page load.

Privacy

setUserConsent

Sets user privacy consent. You must use push with the array syntax to call setUserConsent.

Works in conjunction with the requiresUserConsent init option.

When this option is specified, calls to push are blocked and any method of the SDK results in rejecting Promises until setUserConsent is called with true.

Calling setUserConsent with false blocks the SDK again.

WonderPush.push(["setUserConsent", true]);

clearEventsHistory

Instructs to delete any event associated with the all installations present on the device, locally and on WonderPush servers.

clearPreferences

Instructs to delete any custom data (including installation properties) associated with the all installations present on the device, locally and on WonderPush servers.

clearAllData

Instructs to delete any event, installation and potential user objects associated with all installations present on the device, locally and on WonderPush servers.

downloadAllData

Initiates the download of all the WonderPush data relative to the current installation, in JSON format.

Custom DOM Events

The WonderPush SDK fires a few custom DOM events on the window object. The type of event is always WonderPushEvent and the payload's name property determines what type of WonderPushEvent is emitted.

window.addEventListener('WonderPushEvent', function(event) {
  var eventType = event.detail ? event.detail.name  : undefined;
  // Do something in response to this eventType
});

subscription

The event type subscription allows you to listen to users subscribing and unsubscribing. The value of the event.detail.state property tells you what just happened. It is WonderPush.SubscriptionState.SUBSCRIBED when user just subscribed, WonderPush.SubscriptionState.UNSUBSCRIBED when user just unsubscribed.
This event is fired as soon as the SDK is loaded, to give you the initial state, plus everytime it changes, so you can follow the current state.

For example:

// Store the previous subscription state to observe transitions
var previousWonderPushSubscriptionState;
window.addEventListener('WonderPushEvent', function(event) {
  if (!event.detail || event.detail.name !== 'subscription') return;
  if (previousWonderPushSubscriptionState === WonderPush.SubscriptionState.NOT_SUBSCRIBED && event.detail.state === WonderPush.SubscriptionState.SUBSCRIBED) {
    // Transitioning from not subscribed to subscribed
    console.log('User just subscribed!');
  } else if (previousWonderPushSubscriptionState === WonderPush.SubscriptionState.UNSUBSCRIBED && event.detail.state === WonderPush.SubscriptionState.SUBSCRIBED) {
    // Transitioning from unsubscribed to subscribed
    console.log('User just resubscribed!');
  } else if (previousWonderPushSubscriptionState === WonderPush.SubscriptionState.SUBSCRIBED && event.detail.state === WonderPush.SubscriptionState.UNSUBSCRIBED) {
    // Transitioning from subscribed to unsubscribed
    console.log('User just unsubscribed!');
  } else if (previousWonderPushSubscriptionState === undefined && event.detail.state === WonderPush.SubscriptionState.SUBSCRIBED) {
    // Initial state is subscribed
    console.log('User already subscribed!');
  } else if (previousWonderPushSubscriptionState === undefined && event.detail.state === WonderPush.SubscriptionState.NOT_SUBSCRIBED) {
    // Initial state is not subscribed
    console.log('User not subscribed (yet)!');
  } else if (previousWonderPushSubscriptionState === undefined && event.detail.state === WonderPush.SubscriptionState.UNSUBSCRIBED) {
    // Initial state is unsubscribed
    console.log('User already unsubscribed!');
  }
  previousWonderPushSubscriptionState = event.detail.state;
});

trackEvent

The event type trackEvent allows you to listen to every event send by the WonderPush SDK and react to it.

window.addEventListener('WonderPushEvent', function(event) {
  if (!event.detail || event.detail.name !== 'trackEvent') return;
  console.log('WonderPush event tracked:', event.detail.event);
});

Note that the @NOTIFICATION_OPENED and @NOTIFICATION_RECEIVED events are only triggered inside the Service Worker. You will not be able to listen for them from your website pages. You need to run this code in your Service Worker file.

In-app messaging

setInAppMessagingDisplayCallback

Setting the display callback lets you handle the display of in-app messaging yourself. This method takes a single argument: a function that accepts two arguments:

  • the in-app message to display
  • an InAppMessageReportingCallback object you must call when the in-app is displayed, clicked or dismissed.

Return true when you wish to handle the display yourself, false when you want WonderPush to handle the display.

WonderPush.setInAppMessagingDisplayCallback(function(inApp, reportingCallback) {
     // Display in-app message
     // Report in-app viewed
     // Report any in-app clicks
    return true; // false if you don't want WonderPush to handle the display
});

See handling the display of in-apps yourself for details on how to implement this.

setInAppMessagesSuppressed

Lets you disable or enable in-app messaging.

WonderPush.push(function() {
  // Disables in-app messaging
  WonderPush.setInAppMessagesSuppressed(true);
})

getInAppMessagesSuppressed

Whether in-app messaging is disabled.

Migrating from previous versions of the Website SDK

Previous versions of the Website SDK provided functions called init and ready and most other functions had different names.
Migrating to this new API is automatic, you do not need to do anything to call the new functions. The old ones remain available and you can just call the new ones on the WonderPushSDK object you're used to manipulate.

If you wish to migrate to the new way of doing things, which we recommend, perform all of these steps:

  1. Incorporate the async script tag and snippet
  2. Remove the javascript snippet that looked like (function(w,d,s,i,n)….
  3. Change your call to init to use the array syntax of push.

Change:

// DEPRECATED
WonderPush.init({
    webKey: "YOUR_WEBKEY",
});

to:

// VALID
WonderPush.push(["init", {
    webKey: "YOUR_WEBKEY",
}]);
  1. Change your calls to ready to use the callback syntax of push. To ease the transition, you can also simply alias ready to push like this:
window.WonderPush = window.WonderPush || [];
WonderPush.ready = WonderPush.push;

// You can continue to use `ready` with the same syntax as before
WonderPush.ready(function(WonderPushSDK) {
  // Do something with WonderPushSDK, or WonderPush indifferently
});