Getting Started

This is a developer’s guide for setting up Airship web push notifications.

Setting up your website for web notifications is straightforward. This guide will take you through the required steps to configure your site in the 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.

The 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 Airship service.
  3. For non-secure (non-HTTPS) sites only: An HTML bridge.

Airship supports web push notifications on:

  • Desktop: Google Chrome, Mozilla Firefox, Microsoft Edge, Opera, and Safari
  • Android Mobile: Google Chrome, Mozilla Firefox, Opera
  • iOS and iPadOS Mobile: Safari (iOS and iPadOS 16.4 and above, as a standalone web app)

Resources

Airship Setup

Begin by configuring your site in the dashboard.

 Important

Support for Safari versions older than 16 requires an Apple Safari Web Push certificate in your Airship Web channel configuration.

New to web notifications?

  • If you want to support Safari versions 16 and above only, you do not need to complete additional configuration for Safari. Follow the instructions below and skip step 3.
  • If you want to also support Safari versions older than 16, follow the steps in Apple Safari Web Push certificate, then complete the instructions below, including step 3 for Safari support.

Already using web notifications?

  • If your Web channel is already configured for Safari support, you must maintain your existing Safari certificate to keep supporting existing users who have opted-in to web notifications, even if/when they upgrade to Safari 16 or above.
  • If you have not configured Safari support, you can message users on Safari 16+, with no additional configuration needed and no certificate maintenance required.

  1. Go to Settings » Channels » Web.

  2. Complete the configuration. The preview updates as you enter information. Default fields are required.

    • Default Title: The bolded title that appears above the message body. Typically your brand name.

    • Default Action URL: The URL that opens when a user clicks your message. Typically your brand’s homepage URL.

    • Default Icon URL: Enter the URL for your default icon. If you have CDN enabled, you will see radio buttons to select either Upload Icon or Provide Image URL. See: Media guidelines: Web icon.

    • Secure Bridge: Enable if you have a non-secure (non-HTTPS) website.

    • AMP Support: Enable to support notifications on AMP pages.

       Tip

      You can override your default values on a per message basis via the dashboard or API.

  3. (Optional) Add support for Safari 15.x and below.

    1. Click Add Safari Support.

    2. Enter Allowed Domains. These are the domains that are allowed to request Safari registration permission from the user. Format must include http:// or https://. You may enter the domains as comma-separated or one per line.

    3. Click Choose File, then select your .p12 (Apple Safari Web Push certificate) file.

    4. Enter the certificate password, if any.

  4. Click Save. The button will be labeled Update if you are editing a previous configuration.

  5. Click Download SDK Bundle, and save the zip file.

  6. Unzip the bundle so you can use its files to complete the next steps.

 Important

When you make any edits to your web channel configuration, you must ALSO update your website with the new configuration files. Make sure to complete the final step in the dashboard procedure: download your new SDK bundle. Then you can proceed with the web SDK steps.

Add JavaScript Snippet

Locate file snippet.html in your unzipped SDK bundle and add the file content to all pages of your site.

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.

UA Object

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(sdk => {
 sdk.getChannel().then(channel => {
   console.log("Channel ID: %s", channel.id)
 })
})

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

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

AMP

You can use web notifications with AMP pages in mobile Chrome on Android devices.

 Note

Web notifications do not currently work in AMP pages on Firefox. You can follow the open issue on the AMP project’s Github page.

  1. Once you have created your AMP pages, add the AMP Web Push script to the head of all AMP pages.

    <script async custom-element="amp-web-push" src="https://cdn.ampproject.org/v0/amp-web-push-0.1.js"></script>
  2. Upload the two additional files included in the unzipped SDK bundle to your server: amp-web-push-helper-iframe.html and amp-web-push-permission-dialog.html. You can edit amp-web-push-permission-dialog.html to customize the subscribing and unblocking messages.

  3. Update the AMP-compatible snippet provided in the SDK bundle with the domain URL, and add it only to your APM pages, instead of the regular page snippet.

    /*
      Make sure to replace the placeholders with your domain name in this snippet.
      Also, if you changed the service worker file path, please adapt `service-worker-url` pathname.
    */
    
    <amp-web-push
      id="amp-web-push"
      layout="nodisplay"
      helper-iframe-url="https://REPLACE_WITH_YOUR_DOMAIN/amp-web-push-helper-iframe.html"
      permission-dialog-url="https://REPLACE_WITH_YOUR_DOMAIN/amp-web-push-permission-dialog.html"
      service-worker-url="https://REPLACE_WITH_YOUR_DOMAIN/push-worker.js"
    ></amp-web-push>
  4. (Optional) On AMP pages, you can include a subscribe/unsubscribe button, without the need to include the register function, by including these snippets:

    Subscribe button
    <amp-web-push-widget visibility="unsubscribed" layout="responsive" height="80" width="auto">
      <button class="subscribe" on="tap:amp-web-push.subscribe">
     Subscribe to notifications
      </button>
    </amp-web-push-widget>

    Unsubscribe button
    <amp-web-push-widget visibility="subscribed" layout="responsive" height="80" width="auto">
      <button class="unsubscribe" on="tap:amp-web-push.unsubscribe">Unsubscribe from notifications</button>
    </amp-web-push-widget>

iOS and iPadOS Safari

Apple added Safari support for web push in iOS and iPadOS 16.4. To use web notifications on iOS/iPadOS devices, Apple first requires a user to save the website to their home screen as a web app. This essentially means bookmarking a web page by clicking the Share action and selecting Add to Home Screen. After that, you can direct users to take specific actions to opt in to receiving notifications.

Once opted in, users can manage those permissions per web app/site in their device Notifications settings. The notifications from web apps work exactly like notifications from native iOS and iPadOS apps and appear on the Lock Screen, in Notification Center, and on a paired Apple Watch.

 Important

This is not a comprehensive guide on Home Screen web pages. If you wish to add full support for these features, it’s recommended you see the following articles for further details:

In preparation for sending web push notifications to your iOS and iPadOS users, you will need to configure your site to operate as a web app.

At a minimum, add the following metadata to the head of your pages, which specifies to the browser that an app can run in “standalone” mode:

Site Metadata
<meta name="apple-mobile-web-app-capable" content="yes">
<meta name="mobile-web-app-capable" content="yes">

 Note

The Airship-provided HTML Prompt plugin does not prompt a browser that is in an unsupported context. It does not instruct the user to take any further action.

If you are handling your own opt-in, you may also wish to handle iOS/iPadOS Safari opt-in differently, as calling sdk.register() will fail if the app is not running in standalone mode. The following SDK Properties are available:

  • sdk.isSupported — A boolean. When true, web push is supported by the browser.
  • sdk.canRegister— A boolean. When true, the browser is in a context where registration can happen.

If isSupported is true and canRegister is false, your site may be in a context that disallows registration. You can prompt the user to add the page to their home screen if they wish to receive notifications.

This can also be detected using the Navigator.standalone property, which is only available on iOS/iPadOS Safari, using code similar to the following:

iOS Safari Context Detection
const sdk = await UA

if (sdk.isSupported && !sdk.canRegister) {
   if ('standalone' in navigator) {
      // this is an iOS Safari context; prompt the user
   }
}

Place Service Worker

Web push employs a service worker, which runs as a background process until woken up to perform SDK tasks, e.g., displaying notifications.

Locate the service worker file push-worker.js in your unzipped SDK bundle and place it in the root directory of your site.

It is imperative that you do so 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 the file at 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.

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

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 Airship channels or any registrations tied to any other service worker locations.

Secure Domain Bridge (HTTP Scenarios Only)

If you enabled Secure Bridge when configuring the Web channel for your project, your unzipped SDK bundle will contain the file secure-bridge.html. In mixed-HTTPS situations you will need to add a web-push-secure-bridge.html on your secure domain that contains the contents of the file secure-bridge.html. Make sure your uaSetup() call includes the correct path to it.

Follow the instructions here: Secure Integration.

Send Your First Push Notification

Now that you have configured your project for web push 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: Create a message and Web content.

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

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.getChannel().then(channel => 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.
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.
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 Push Title",
         "require_interaction": true,
         "icon": {
            "url": "https://example.com/icon.png"
         }
      }
   }
}

Push to Multiple Platforms

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.

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 Push Title",
         "require_interaction": true,
         "icon": {
            "url": "https://example.com/icon.png"
         }
      }
   }
}

Additional Resources

Web SDK

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

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

UaSDK

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

Register

Follow these steps to register the current browser with 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 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.

Example registration
UA.then(sdk => {
  sdk.register() // Returns Channel object
})

Filter Out Non-Compliant Browsers

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

Example filter
UA.then(sdk => {
  sdk.isSupported // Returns bool
})

Validate Browser Support and Security

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

Example
UA.then(sdk => {
  sdk.canRegister // Returns bool
})

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

 Note

Safari can register Safari users with 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 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

The method sdk.getChannel() returns the channel for the current user as soon as it is created (new registration) or loaded (existing registration). Unsupported browsers will call .catch().

Example
UA.then(sdk => {
  sdk.getChannel().then(channel => {
    // Return the current Channel ID
    channel.id // Returns String

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

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

Event Listeners

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

 Note

If you intend to set attributes, tags, named user, or anything that could modify the channel within your event listener, make sure to set the once option to true in order to prevent an infinite loop.

UA.then(sdk => {
  sdk.addEventListener('channel', ev => {
    ev.channel === sdk.channel
  }, { once: true })
})

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

UA.then(sdk => {
  sdk.addEventListener('tags', ev => {
    console.log(ev.detail) // print all tags that have been set client side
  })
})

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.

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

Create an Apple Safari Web Push certificate

 Important

Support for Safari versions older than 16 requires an Apple Safari Web Push certificate in your Airship Web configuration.

To create an Apple Safari Website Push certificate, you will need:

  • An Apple Developer account
  • A Certificate Signing Request (CSR). If you don’t already have this file saved locally, follow Apple’s instructions to create one.

First, create a web push ID and download your SSL certificate:

  1. Log in to your Apple Developer account.
  2. Go to Account » Certificates, Identifiers & Profiles.
  3. Select Identifiers in the sidebar and click to create a new Identifier.
  4. Select Website Push IDs and click Continue.
  5. Enter a description and a unique identifier, then click Continue.
  6. Confirm your description and identifier are correct and click Register.
  7. Select your new web push identifier from the list.
  8. Click Create Certificate under Production Certificates. This will generate a Website Push Notification service SSL (Sandbox & Production) certificate compatible with both the Production and Development environments.
  9. Select Choose File and upload your CSR file, then click Continue.
  10. Click Download and save the SSL certificate file for use in the next step. You may need to reload the page if the Download button is not yet active.

Next, install your certificate, export it as a p12 file, and create a password:

  1. Open the certificate you downloaded in the previous step. It should open in the Keychain Access app and be listed in My Certificates.
  2. Click the certificate in the list, then go to the File menu and select Export Items….

    Also be sure to select My Certificates category in the sidebar. If My Certificates is not highlighted, you will not be able to export the certificate as a .p12 file.

  3. Save the file in the Personal Information Exchange (.p12) format.

    You will be prompted to create a certificate password, which you will enter when you upload the .p12 file in the Airship dashboard.

Now you can upload the p12 file and provide the password when configuring the Web channel in the Airship dashboard.