The WonderPush Developer Hub

Welcome to the WonderPush developer hub. You'll find comprehensive guides and documentation to help you start working with WonderPush as quickly as possible, as well as support if you get stuck. Let's jump right in!

Get Started    

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.
### 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.

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.

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
language StringThe language code. We currently support "en" and "fr". All strings can be configured using the bell options.
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:


[block:image]
{
  "images": [
    {
      "image": [
        "https://files.readme.io/cee8c93-switch.png",
        "switch.png",
        1000,
        76,
        "#f2f2f2"
      ]
    }
  ]
}
[/block]




[block:parameters]
{
  "data": {
    "h-0": "Parameter",
    "h-1": "Type",
    "h-2": "Description",
    "0-0": "`parentNode`",
    "0-1": "HTMLElement",
    "0-2": "The node where we'll put the subscription switch using `appendChild`.",
    "1-0": "`options`",
    "1-1": "Object",
    "1-2": "Customize the appearance of the subscription switch. See [`subscriptionSwitch` init options](#section-subscription-switch-options)."
  },
  "cols": 3,
  "rows": 2
}
[/block]

#### Subscription Switch Options

Most of these initialization options can be specified within your call to [`init`](#section-init) inside the `subscriptionSwitch` field, or directly in your call to [`showSubscriptionSwitch`](#section-show-subscription-switch), to the exception of `switchElementId` that can only be specified at init time.


[block:parameters]
{
  "data": {
    "h-0": "Option",
    "h-1": "Type",
    "h-2": "Description",
    "0-0": "`switchElementId`",
    "0-1": "String",
    "0-2": "The 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.",
    "1-0": "`classPrefix`",
    "1-1": "String",
    "1-2": "The prefix to prepend to all the CSS classes names used. Defaults to `wp-`.",
    "2-0": "`prepend`",
    "2-1": "String",
    "2-2": "Optional HTML code to inject before the actual switch element.",
    "3-0": "`append`",
    "3-1": "String",
    "3-2": "Optional HTML code to inject after the actual switch element.",
    "4-0": "`sentence`",
    "4-1": "String",
    "4-2": "HTML snippet to inject in a SPAN tag right before the switch.",
    "5-0": "`cssClass`",
    "5-1": "String",
    "5-2": "CSS class to add to the switch element.",
    "6-0": "`on`",
    "6-1": "String",
    "6-2": "Label of the switch in the ON state.",
    "7-0": "`off`",
    "7-1": "String",
    "7-2": "Label of the switch in the OFF state.",
    "8-0": "`colorOn`",
    "8-1": "String",
    "8-2": "Name of a predefined color to use for the ON state. Valid values are `blue` and `green`. Defaults to `blue`.",
    "9-0": "`colorOff`",
    "9-1": "String",
    "9-2": "Name of a predefined color to use for the OFF state. Valid values are `gray`, `grey` or `red`. Defaults to `gray`."
  },
  "cols": 3,
  "rows": 10
}
[/block]

### `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:



[block:code]
{
  "codes": [
    {
      "code": "<script>\n  window.WonderPush = window.WonderPush || [];\n\tWonderPush.push(function() {\n  \tWonderPush.showTagSwitches(document.body, [\n      {sentence: 'Sports: ', tag: 'sports'},\n    ]);\n  });\n</script>",
      "language": "javascript"
    }
  ]
}
[/block]

Would be equivalent to:


[block:code]
{
  "codes": [
    {
      "code": "<div class=\"wonderpush-tag-switch\"\n     data-sentence=\"Sports: \"\n     data-tag=\"sports\"></div>",
      "language": "html"
    }
  ]
}
[/block]

And would render something like this:


[block:image]
{
  "images": [
    {
      "image": [
        "https://files.readme.io/341365a-Screenshot_2019-11-26_at_17.31.31.png",
        "Screenshot 2019-11-26 at 17.31.31.png",
        304,
        88,
        "#ecf1f4"
      ]
    }
  ]
}
[/block]




[block:parameters]
{
  "data": {
    "h-0": "Parameter",
    "h-1": "Type",
    "h-2": "Description",
    "0-0": "`parentNode`",
    "0-1": "HTMLElement",
    "0-2": "The node where we'll put the tag switches using `appendChild`.",
    "1-0": "`options`",
    "1-1": "Array<Object>",
    "1-2": "Specify the switches. See [`tagSwitch` options](#section-tag-switch-options)."
  },
  "cols": 3,
  "rows": 2
}
[/block]

#### 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.


[block:parameters]
{
  "data": {
    "h-0": "Option",
    "h-1": "Type",
    "h-2": "Description",
    "0-0": "`tag`",
    "0-1": "String",
    "0-2": "The name of the tag to manipulate. Either this option or both `field` and `value` must be given.",
    "4-0": "`prepend`",
    "4-1": "String",
    "4-2": "Optional HTML code to inject before the actual switch element.",
    "5-0": "`append`",
    "5-1": "String",
    "5-2": "Optional HTML code to inject after the actual switch element.",
    "6-0": "`sentence`",
    "6-1": "String",
    "6-2": "HTML snippet to inject in a SPAN tag right before the switch.",
    "7-0": "`cssClass`",
    "7-1": "String",
    "7-2": "CSS class to add to the switch element.",
    "8-0": "`on`",
    "8-1": "String",
    "8-2": "Label of the switch in the ON state.",
    "9-0": "`off`",
    "9-1": "String",
    "9-2": "Label of the switch in the OFF state.",
    "10-0": "`colorOn`",
    "10-1": "String",
    "10-2": "Name of a predefined color to use for the ON state. Valid values are `blue` and `green`. Defaults to `blue`.",
    "11-0": "`colorOff`",
    "11-1": "String",
    "11-2": "Name of a predefined color to use for the OFF state. Valid values are `gray`, `grey` or `red`. Defaults to `gray`.",
    "3-0": "`classPrefix`",
    "3-1": "String",
    "3-2": "The prefix to prepend to all the CSS classes names used. Defaults to `wp-tag-`.",
    "1-0": "`field`",
    "1-1": "String",
    "1-2": "The name of the property to manipulate. Either this option along with `value`, or `tag` must be given,",
    "2-0": "`value`",
    "2-1": "String",
    "2-2": "The value to manipulate in the `field`-named property. Either this option along with `field`, or `tag` must be given,"
  },
  "cols": 3,
  "rows": 12
}
[/block]

### 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](doc:cross-domain-subscription).


[block:image]
{
  "images": [
    {
      "image": [
        "https://files.readme.io/1705162-cross-domain-popup.png",
        "cross-domain-popup.png",
        1002,
        1058,
        "#f0f0f1"
      ],
      "sizing": "80"
    }
  ]
}
[/block]

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](#section-cross-domain-popup-window).


[block:parameters]
{
  "data": {
    "h-0": "Option",
    "h-1": "Type",
    "h-2": "Description",
    "0-0": "`externalBoxMessage`",
    "0-1": "String",
    "0-2": "The main message below your website name. Defaults to “We'd like to send you notifications”.",
    "1-0": "`externalBoxExampleTitle`",
    "1-1": "String",
    "1-2": "The title of the example notification. Defaults to “Example notification”.",
    "2-0": "`externalBoxExampleMessage`",
    "2-1": "String",
    "2-2": "The message of the example notification. Defaults to “This is an example notification”.",
    "3-0": "`externalBoxDisclaimer`",
    "3-1": "String",
    "3-2": "The fineprint displayed below the example notification. Defaults to “You can always unsubscribe at anytime.”.",
    "4-0": "`externalBoxProcessingMessage`",
    "4-1": "String",
    "4-2": "The message written when user accepts and subscription is in progress. Defaults to “Subscribing...”.",
    "5-0": "`externalBoxSuccessMessage`",
    "5-1": "String",
    "5-2": "The message displayed when subscription is successful. Defaults to “Thanks for subscribing!”.",
    "6-0": "`externalBoxFailureMessage`",
    "6-1": "String",
    "6-2": "The default error message when subscription fails. Defaults to “Sorry, something went wrong.”.",
    "7-0": "`externalBoxTooLongHint`",
    "7-1": "String",
    "7-2": "The error message displayed when subscribing takes too long. Defaults to “Poor connection or private browsing?”.",
    "8-0": "`positiveButtonText`",
    "8-1": "String",
    "8-2": "The text of the subscription button (shown on Firefox only)",
    "9-0": "`negativeButtonText`",
    "9-1": "String",
    "9-2": "The text of the cancel button (shown on Firefox only)"
  },
  "cols": 3,
  "rows": 10
}
[/block]

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;
});

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",
}]);
4. Change your calls to `ready` to use the [callback syntax](#section-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
});

Updated about a month ago

Website SDK Reference


Website SDK Javascript Reference

Suggested Edits are limited on API Reference Pages

You can only suggest edits to Markdown body content, but not to the API spec.