Web Notify

The Urban Airship Web SDK is hosted on a secure CDN (content delivery network). In order to enable web push notifications you will add two components to your site, and optionally a third component for sites that aren't fully HTTPS:

  1. An asynchronous loading snippet that allows use of the SDK before and after it is fully loaded.

  2. A service worker that handles incoming push requests and communicates with the Urban Airship service.

  3. For non-secure (non-HTTPS) sites only: An HTML bridge.

Resources


Note

Supported Browsers

  • Desktop: Google Chrome, Mozilla Firefox, Opera, and Safari.

  • Android Mobile: Google Chrome, Mozilla Firefox, Opera, Microsoft Edge.

Getting Started

Setting up your website for web notifications is straightforward. This guide will take you through the required steps to configure your site in the Urban Airship dashboard and add the required components to begin registering users for notifications.

Note

An additional step is required if your site is not fully HTTPS. We'll provide a workaround script for these sites during the setup process. This workaround is not required for non-HTTPS sites on Safari.

Urban Airship Setup

Begin by configuring your site for Web Notify in the dashboard.

  1. Complete the steps in Configure Web Notify. When you complete these steps, your setup files will be placed in a ZIP file.

  2. Unzip the downloaded file to access your setup files for the remaining steps.

Add JavaScript Snippet

snippet.html

<script type="text/javascript">
!function(n,t,c,e,u){function r(n){try{f=n(u)}catch(n){return h=n,void i(p,n)}i(s,f)}function i(n,t){for(var c=0;c<n.length;c++)d(n[c],t);
}function o(n,t){return n&&(f?d(n,f):s.push(n)),t&&(h?d(t,h):p.push(t)),l}function a(n){return o(!1,n)}function d(t,c){
n.setTimeout(function(){t(c)},0)}var f,h,s=[],p=[],l={then:o,catch:a,_setup:r};n[e]=l;var v=t.createElement("script");
v.src=c,v.async=!0,v.id="_uasdk",v.rel=e,t.head.appendChild(v)}(window,document,'https://web-sdk.urbanairship.com/notify/v1/ua-sdk.min.js',
  'UA', // This value can be changed to use a custom variable name.
  {
  appKey: 'YOUR-APP-KEY',
  token: 'BEARERTOKEN-FROM-UA',

  // Safari Web Push only
  websitePushId: 'WEBSITE-PUSH-ID-FROM-UA',
  // Open Web Push Protocol only.
  vapidPublicKey: 'WEB-PUSH-KEY-FROM-UA',
  // Only needed when used on insecure hosts:
  secureIframeUrl: 'https://your.secure.domain/path/to/web-push-secure-bridge.html'
  })
</script>

In your unzipped directory, locate snippet.html. This file provides an asynchronous loading snippet that allows use of the Web SDK before it loads, and comes populated with the configuration values required for your site.

You should place the snippet on all pages of your site.

UA Object

UA.then(function(sdk) {
  console.log(sdk.channel.id)
}).catch(function(err) {
  console.log(err)
})

// Multiple calls have no additional expense.
UA.then(function(sdk) {
  $('#register').show()
  $('#register').click(function(ev) { sdk.register() })
})

The loading snippet adds a UA object to the global scope. This object provides promise-like then and catch functions. They can be called as many times as you'd like and can be chained like promises.

UA.then(cb) Takes a callback function that is called with sdk as its only argument. It is only called if the SDK loads successfully and the browser supports all features. All other features of the SDK can be used from here.

UA.catch(cb) Takes a callback function that is called with the error object as its only argument. It is only called if the SDK encounters an error while loading or the browser is unsupported.

UA.then will only be called when the SDK has been loaded and if the browser supports the SDK's features. Do not rely on it being called in every browser. Because of this it is good practice to not enable UA SDK-specific parts of your UI until the SDK has loaded.

Unsupported browsers will call .catch(), which likewise will only be called if loading the SDK has an error.

Service Worker

push-worker.js

importScripts('https://web-sdk.urbanairship.com/notify/v1/ua-sdk.min.js')
uaSetup.worker(self, {
  appKey: 'YOUR-APP-KEY',
  vapidPublicKey: 'WEB-PUSH-KEY-FROM-UA',
  token: 'BEARERTOKEN-FROM-UA',

  // The icon and title that your push notification will use if the
  // notification payload does not include them.
  defaultIcon: 'https://upload.wikimedia.org/220px-Urban_Airship_Logo.jpg',
  defaultTitle: 'My Cool Website',

  // A URL that clicking a notification will open if you select "Home Page"
  // as your action. If no url is supplied clicking a notification will simply
  // close it.
  defaultActionURL: 'https://example.com',
})

When configured for Open Web Push Protocol browsers (Chrome, Firefox, Opera, Edge), Web Notify employs a service worker, which runs as a background process until woken up to perform SDK tasks, e.g., displaying notifications.

Note

When desktop Safari is the only browser configured for Web Notify, there is no service worker.

A service worker called push-worker.js is one of the setup files generated when you configure your project for Web Notify in Urban Airship Setup.

Tip

For further reading on service workers, see these excellent primers from Google and Mozilla:

Service Worker Location

It is imperative that you place the service worker in the root directory of your site at the beginning of your implementation so that your entire website is within the scope of the worker.

The JavaScript snippet that you added to your site pages contains a URL for push-worker.js** and assumes it is placed in the root.

If you are unable to place it in the root, your entire site may not be able to access the service.

If you need to combine the push worker with an existing service worker, you may need to specify a new location for your worker file. You can do this by adding a workerUrl: '/service-worker.js', setting to your on-page snippet, inside your service worker, and to your secure-bridge.html if you're using one.

Troubleshooting: Duplicate Web Notifications

If for any reason you have moved the service worker, e.g., from a non-root location to the root directory, users may receive duplicate push notifications.

This is because users may have a browser-cached service worker running even though the file has been moved, and subscriptions are tied to push worker location. If they register again with the new (or newly-moved) service worker, they will have a new channel ID.

 

Add a new push-worker.js in prior location of service worker to unsubscribe users from duplicate notifications:

self.onactivate = function (ev) {
  self.registration.pushManager.getSubscription().then(subscription => {
    if (subscription) {
      subscription.unsubscribe()
    }
  })
}

To help out in situations like this, we have provided a bit of code (think of it as a “cleanup” service worker) that can be placed at the location of the original service worker. The process here is simple. All you have to do is put this code in a push-worker.js file placed where your previous service worker lived.

Once you’ve done this, browsers will detect the change and unsubscribe any subscriptions tied to that worker location. And don’t worry, this will not affect your Urban Airship channels or any registrations tied to any other service worker locations.

Secure Domain Bridge (HTTP Scenarios Only)

secure-bridge.html

<!DOCTYPE html>
<html><head></head><body>
    <script type="text/javascript" rel="secureBridge" src="https://web-sdk.urbanairship.com/notify/v1/ua-sdk.min.js"></script>
    <script type="text/javascript">uaSetup.secureBridge({
        appKey: 'YOUR-APP-KEY'
    })</script>
</body></html>

If you checked the Secure Bridge box when configuring your Open Web Push Protocol push in step 1, you will have secure-bridge.html in your setup files.

Note

If you configure Safari only, you will not have a Secure Bridge option.

In mixed-HTTPS situations you will need to add a web-push-secure-bridge.html on your secure domain that contains this HTML, and make sure your uaSetup() call includes the correct path to it.

See these instructions to complete this step, if necessary: Secure Integration.

User Registration

A user is registered when they opt in to receiving notifications via the system dialog, which varies slightly from browser to browser. This is an example Chrome browser registration dialog:


The dialog is presented when the page invokes the sdk.register function. As a best practice, we discourage calling this function on page load, before the user has had a chance to assess the potential usefulness of notifications from your site. See Registration UI for a simple, sample UI element that registers a user.

In any case, this moment when a user decides whether to allow or block notifications is when we will either register a channel for them with an opt-in status, or not.

The SDK returns this registration event to Urban Airship, along with the user's registration status and certain metadata, namely device property tags. When you send a push notification to a web user, their registration status is returned to Urban Airship via the push service.

Registration Status

Note

Analytics must be enabled to determine registration status. See: Analytics and Reporting.

A user's registration status is one of:

  • Opted-in: Allowed notifications and has not subsequently disallowed them, either via browser settings or by calling the optOut() method.
  • Opted-out: Initially allowed notifications but subsequently disabled them.
  • Uninstalled: A user is considered to be Uninstalled if they have both:

    1. Opted out via the browser settings, AND
    2. Not returned to the website.


A user can change their opt in/out status in two places:

  1. The browser's settings.
  2. The website's registration UI.

Registration UI

Sample Registration UI:

<button id="register">Sign up for notifications</button>
<script>
   document.getElementById('register').addEventListener('click', function(){
     UA.then(function(sdk) {
      sdk.register()
     })
   })
</script>

You are responsible for providing a UI to register a user. While it is possible to call the registration on page load, we strongly discourage this behavior. If a user is immediately presented with a notification permission dialog without knowing what notifications to expect, chances are higher that they will decline, making it difficult to reengage with them in the future.

Consider requesting permission during a workflow that is germane to notifications, and, when possible, providing a utility to opt out (and back in) that doesn't involve digging into the browser settings.

Web SDK

This section is an introduction to the Web Notify SDK and associated methods.

Please visit our Urban Airship Web Notify SDK Reference for a complete reference.

UaSDK

The main Web Notify SDK object. It can not be instantiated manually. It is returned by the async loader.

Register

UA.then(function(sdk) {
  sdk.register() // Returns Channel object
})

Register the current browser with Urban Airship.

  • Fetch the browser's subscription object, prompting the user for permission if necessary.

  • Collect browser information for out-of-the-box tag segmentation.

  • Register with Urban Airship and resolve the returned channel object.

  • Resolves an error that can be caught if there is an error while registering or the browser is not a secure context. See canRegister.

 

Filter Out Non-Compliant Browsers

UA.then(function(sdk) {
  sdk.isSupported // Returns bool
})

Filters out any browsers that do not support web push. The SDK is supported on HTTP locations where it can NOT register, provided that the secure bridge is enabled.

 

Validate Browser Support and Security

UA.then(function(sdk) {
  sdk.canRegister // Returns bool
})

This is true if the browser isSupported and if window.isSecureContext is true.

Make sure that the current browser has web push features AND is in a secure context capable of attempting registration.

Note

Safari can register Safari users with Urban Airship from insecure domains without the use of the secure bridge. Any domain that is running the SDK and configured in the Allowed Domains section of the Safari configuration in Urban Airship can register Safari users. The SDK cannot verify that it is on an allowed domain before attempting to register users. Attempting to register users on a domain that is not explicitly allowed in your Safari configuration will fail.

Channel Object

UA.then(function(sdk) {
  // Return the current Channel ID
  sdk.channel.id // Returns String

  // Return the opted-in status
  sdk.channel.optedIn // Returns bool

  // Opt this device out of Web Notify
  sdk.channel.optOut() // Returns true if successful
  // In order to opt back in you must call `sdk.register()` again.
})

If a browser has registered, sdk.channel will give you the channel object for that browser.

sdk.channel returns null if unregistered.

Event Listeners

UA.then(function(sdk) {
  sdk.addEventListener('channel', function(ev) {
    ev.channel === sdk.channel
  })
})

The main SDK object fires a channel event when a channel is registered, loaded or changed.

 

UA.then(function(sdk) {
  sdk.addEventListener('tags', function(ev) {
    ev.tags === sdk.channel.tags.list
  })
})

The main SDK object fires a tags event any time the tags change.

 

UA.then(function(sdk) {
  sdk.addEventListener('push', function(ev) {
    // ev.push is the push payload object
  })
})

If you are on an HTTPS page that is in-scope of your push-worker.js: The main SDK object fires a push event when the browser receives a push.

Analytics and Reporting

Our Web SDK comes with analytics support out of the box, and by default, there are no explicit preferences you need to set in order to enable reporting. The integration is handled automatically unless you set disableAnalytics to true.

Custom Events

Custom Events are available out of the box and ship with the Web Notify SDK. See our CustomEvent class reference for complete details.

Custom Events require Analytics to be enabled, which is the default setting. If you disable analytics, no Custom Events will be recorded.

We provide convenient templates to track common sorts of events. See Custom Event Templates for more information.

Disable Analytics

When the website has disabled analytics in the SDK at the website level or for an individual user, no analytics events will be sent to Urban Airship. Analytics events includes things like sessions, clicks, and custom events.

UA.then(function(sdk) {
  sdk.disableAnalytics = true
})

To disable analytics for a specific browser/user:

 

disableAnalytics: true

If it is necessary to disable analytics for an entire install set disableAnalytics to true in both the snippet and push-worker configuration.

Addressing Devices

To help target specific devices or users for a notification, we have Tags, Named Users and Tag Groups.

Tags

Modifying tags:

// Set tags
UA.then(function(sdk) {

  // List all tags
  sdk.channel.tags.list // Returns {device: [tag1, tag2, ...], custom-group: [tag]}

  // Check for a specific tag
  sdk.channel.tags.has(tag, group) // Returns bool

  // Add a tag
  sdk.channel.tags.add(tag, group) // Returns true if successful

  // Remove a tag
  sdk.channel.tags.remove([tag1, tag2, ...], group) // Returns True if successful

  // Set tags
  sdk.channel.tags.set(tags, group) // Returns true if successful
  // Resets all tags for the given tag group.

  // `group` is optional in all tag functions and defaults to `device` if not specified

})

Tags are an easy way to group channels. Many tags can be applied to one or more devices. Then, a message sent to a tag will be sent out to all devices that are associated with that tag.

Named Users

Setting the named user:

UA.then(function(sdk) {

  // Return the current Named User
  sdk.channel.namedUser.id  // Returns null or string

  // Set the Named User to a String
  sdk.channel.namedUser.set(name) // associates this channel with a named user

  // Remove the currently associated Named User
  sdk.channel.namedUser.remove() // Disassociates the channel from the named user
  // Returns true if successful

})
Note

Associating the channel with a Named User ID, will implicitly disassociate the channel from the previously associated Named User ID, if it existed.

Named Users allow you to associate multiple devices to a single user or profile that may be associated with more than one device, e.g., an end-user's Chrome browser on their laptop and their iPhone. A device can have only one Named User, and a single Named User should not be associated with more than 50 devices. Named Users provide the ability to directly set tags on them (see Tag Groups).

By default, Named Users can only be associated server-side. A 403 Forbidden response is returned if Named User association is attempted when client-side association is disabled. In order to associate a Named User through the project, you must change the project's Named User security setting to allow Named Users to be set from devices. Please visit the Settings documentation to enable this option.

Tag Groups

Channel Tag Group Example:

UA.then(function(sdk) {

  // Add a tag to a group
  sdk.channel.tags.add('tag-name', 'group-name')

  // Remove a tag from a group
  sdk.channel.tags.remove('tag-name', 'group-name')

  // Set tags on a group
  sdk.channel.tags.set(['silver-member', 'gold-member'], 'group-name')
  // Resets all tags for the given tag group.

})

Tag groups are configurable namespaces for organizing tags for the channel and Named User. Please view the Tag Groups documentation for more details. The Create and push to a tag group guides you through creating and using Tag Groups.

By default, Tag Groups can only be modified from the server. A 403 Forbidden response is returned if Tag Groups modification is attempted when client-side Tag Groups is disabled. In order to modify Tag Groups through the application, you must change the application's Tag Group security settings to allow these tags to be set from devices. Please visit the Settings documentation to enable this option.

Send a Web Push

Now that you have configured your project for Web Notify and are able to register users, it's time to send a test notification. You can do this via either the dashboard or our API.

To send a push via the dashboard, see the Web Notify Tutorial.

To send a web push via our API, two examples are provided below, one only to web browsers, and one to web, iOS, and Android.

Web Only Push

Example Request: Web only push

POST /api/push HTTP/1.1
Authorization: Basic <master authorization string>
Content-Type: application/json
Accept: application/vnd.urbanairship+json; version=3;

{
   "audience": {
      "channel": "<YOUR_CHANNEL_ID>"
   },
   "device_types": [
      "web"
   ],
   "notification": {
      "alert": "Hello, Web!",
      "web": {
         "title": "My First Web Notify Title",
         "require_interaction": true,
         "icon": {
            "url": "https://example.com/icon.png"
         }
      }
   }
}

In this example, we will introduce the push object, the required request body for sending a notification via the push API, using the three required attributes audience, device_types, and notification.

Audience
We'll start with the simplest audience selector possible: an individual channel ID. For testing purposes, you can retrieve your channel ID from a registered browser by entering UA.then(sdk => console.log(sdk.channel.id)) in the JavaScript console.
Device Types
Since we are only sending to web devices, we will specify the "web" device type as an array of one. In the next example, we will include additional device types.

Alternatively, you could specify the special string "all", which maps to all configured platforms for your project, e.g., "device_types": "all".
Notification
Finally, we will specify the values for our test notification, including the alert text, and web push-specific attributes that we will include in the web platform override object. Platform overrides can be used either to override a value for a specific platform or to specify values that are only applicable to that platform.

Push to Multiple Platforms

Example Request: Push to multiple platforms

POST /api/push HTTP/1.1
Authorization: Basic <master authorization string>
Content-Type: application/json
Accept: application/vnd.urbanairship+json; version=3;

{
   "audience": {
      "named_user": "sven_svensson"
   },
   "device_types": [
      "web",
      "ios",
      "android"
   ],
   "notification": {
      "alert": "Hello, World!",
      "web": {
         "alert": "Hello, Web!",
         "title": "My First Web Notify Title",
         "require_interaction": true,
         "icon": {
            "url": "https://example.com/icon.png"
         }
      }
   }
}

This example illustrates sending a push notification to a named user, "sven_svensson", who is registered on multiple platforms, including web.

In the top-level notification attribute of the payload, the value for the alert property is "Hello, World!". Since we want our web users to experience the most relevant content possible, we are going to use the web override on the notification object to specify the more appropriate "Hello, Web!" alert message for web users.

Additional Resources

CMS Integrations

We provide a WordPress plugin and a Drupal module to simplify the Web Notify integration process for those platforms. Setup instructions are provided for each.

Note

CMS integrations are not supported for Safari at this time.

WordPress Setup

  1. Configure your site for Web Notify via the UA dashboard, following the steps in Urban Airship Setup, and download your ZIP file.

  2. Navigate to the Plugins tab of your WordPress admin dashboard and install our Urban Airship Web Push Notifications plugin.
    Note

    If your WordPress site is not HTTPS, please see our documentation on Secure Integration for details on how to securely host the necessary files and registration page.

  3. Navigate to the plugin's Settings page, upload the SDK Bundle ZIP file that you downloaded in Step 1, and enter the App Master Secret for your Urban Airship project.

    You'll know you've done this successfully if you get green checkmarks next to both items under Service Connectivity.
    Tip

    Your Urban Airship project's App Master Secret is in the Settings menu.

    Open your project from go.urbanairship.com/apps/, click Settings and choose APIs & Integrations, then copy the App Master Secret for use in the WordPress setup.

  4. Configure optional settings, including how you'd like to prompt your site visitors to opt in to notifications.

    • Our WordPress plugin offers a CSS Class that can be used to add a custom opt-in prompt or button to your site.

    • You can also use the Opt-In Prompt settings to customize when to show your users the default browser prompt, e.g., after 3 page views.

Now that you've finished setup, you're ready to start sending notifications. You may send notifications from the Urban Airship dashboard, or directly from your WordPress admin page. Our plugin includes the ability to automatically send a web push notification when publishing or updating any public post type (including custom post types) on your WordPress site as well as the ability to send a one-off web push notification at any time from your Wordpress dashboard using our custom content type.

Drupal Setup

  1. Configure your site for Web Notify via the UA dashboard, following the steps in Urban Airship Setup, and download your ZIP file

  2. Navigate to your Drupal dashboard and install our Urban Airship Web Push Notifications module. The module supports both Drupal 7 and 8.
    Note

    If your Drupal site is not HTTPS, please see our documentation on Secure Integration for details on how to securely host the necessary files and registration page.

  3. Navigate to the module's settings page (Configuration » Web Services » Urban Airship Web Push Notifications), and:

    • On the Credentials tab, enter your Urban Airship App Key and App Master Secret.

    • On the SDK Bundle tab, upload the SDK Bundle ZIP file that you downloaded in Step 1.

    • On the Opt-In Prompt tab, choose how you'd like to prompt your site visitors to opt-in to notifications. Either use a custom Modal, Banner, or Button to prompt your visitors, or check the "Do Not Use Custom Opt-In Prompt" box to use the default browser prompt.

      You may also choose where on the page to display your prompt and when to display it, e.g., after 3 page views. Note: You cannot customize the location of the default browser prompt.

      Tip

      Your Urban Airship project's App Key and Master Secret are in the Settings menu.

      Open your project from go.urbanairship.com/apps/, click Settings and choose APIs & Integrations, then copy the App Key and Master Secret for use in the Drupal setup.

  4. Enable notifications for specific content types. Navigate to Structure » Content Types, and click to select a desired Content Type, such as 'Article'. For each selected content type, on the Edit tab, select Urban Airship Web Push Notifications, then check the box for "Enable Notifications." You may also set the content type's default notification text, such as the Node Title.

Now that you've finished setup, you're ready to start sending notifications. You may send notifications from the Urban Airship dashboard, or directly from the Drupal UI. Our module includes the ability to automatically send a web push notification when publishing or updating any piece of content on your Drupal site, as well as the option to schedule a notification for a date and time in the future.

Tag Manager Integrations

Deploy Web Notify on your site using third-party tag managers.

Note

Tag manager integrations are not supported for Safari at this time.

Important

Google Tag Manager and Ensighten are supported today. Tealium support and documentation for each integration are coming soon.

Google Tag Manager

The Urban Airship Web Notify SDK can be implemented using Google Tag Manager.

This section assumes that you have already completed the following steps at the beginning of this guide:

  1. Urban Airship Setup
  2. Add push-worker.js to your root directory
Important

The push worker must be placed at the root of the server. Its function is to create and sustain what is called a service worker, which provides a safe and secure way to interact with a site as a background task. These files cannot be managed within the Google Tag Manager environment, as they live at a level above HTML content and must be directly accessible rather than imported into a page.

The remaining steps are handled through the Google Tag Manager interface.

Install Google Tag Manager

  1. In Google Tag Manager, select your container, click Admin in the navigational header, then click Install Google Tag Manager.

  2. Follow Google's instructions to add Google Tag Manager to any HTTPS-delivered page.

Configure Your Web Notify Tag

<script type="text/javascript">

  var options = {}
  options.appKey = '<Your App Key>';
  options.token = '<your token from sample.html>';
  options.vapidPublicKey = atob('<base 64 encoded vapidPublicKey>');

  // Optional timestamp and signature for the tag
  // 86acbd31cd7c09cf30acb66d2fbedc91daa48b86:1494532191.21

  !function(n,t,c,e,u){function r(n){try{f=n(u)}catch(n){return h=n,void i(p,n)}i(s,f)}function i(n,t){for(var c=0;c<n.length;c++)d(n[c],t);
  }function o(n,t){return h?(d(t,h),l):f?(d(n,f),l):(n&&s.push(n),t&&p.push(t),l)}function a(n){return o(!1,n)}function d(t,c){
  n.setTimeout(function(){t(c)},0)}var f,h,s=[],p=[],l={then:o,catch:a,_setup:r};n[e]=l;var v=t.createElement("script");
  v.src=c,v.async=!0,v.id="_uasdk",v.rel=e,t.head.appendChild(v)}(window,document,'https://web-sdk.urbanairship.com/notify/v1/ua-sdk.min.js',
      'UA', options);

</script>

Next, we will configure a new tag in your newly-created Google Tag Manager container, using the Custom HTML tag type.

  1. Click Workspace in the navigational header, then click the New Tag pane.

  2. Enter "Web Notify" in the title field, then click the Tag Configuration pane.

  3. Click the tag type Custom HTML, then paste the code in the right column into the HTML field.

    • Replace all bracketed values in the provided GTM code, e.g., <Your App Key>, with the corresponding values for your site. You can find them in your push-worker.js file.
    • Do not check the box for Support document.write

Choose a Trigger

<!-- The following code provides a button to test your GTM implementation of Web Notify -->

<h2>Web Notify Test Page</h2>

<p id="register_p">
  <button id='register'>
    Sign up for notifications
  </button>
</p>

<script type="text/javascript">
  document.getElementById('register').addEventListener('click', function(){
     UA.then(function(sdk) {
      sdk.register()
     })
   });
</script>
  1. Click the Triggering pane, then click the row for All Pages. You can edit this later, if desired.

  2. Click the Save button, and you will be returned to the Workspace.

  3. Click the Submit button.

  4. Enter a Version name and description for this submission's changes, then click the Publish button.

  5. Test to see if notifications are working, using the provided Sign up for notifications button code.