Getting Started

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

Set up your project to register users for Web Push NotificationsA message that appears in the top or bottom right corner of a web browser or in a notification center.On mobile devices, web push notifications appear similar to push notifications. and Web ScenesA single or multi-screen in-app experience cached on users’ devices and displayed when users meet certain conditions in your app or website, such as viewing a particular screen or when a Custom Event occurs. They can be presented in fullscreen, modal, or embedded format using the default swipe/click mode or as a Story. Scenes can also contain survey questions.. Both are referred to generally as “notifications” and “web notifications” on this page.

Airship supports web push notifications and Scenes on:

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

The Airship Web SDK is hosted on a secure content delivery network (CDN).

In order to enable these notifications, you will add two components to your site:

  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.

Resources

Airship Setup

 Important

Airship Web SDK v2 was released August 1, 2024.

Removed support for Web SDK v2:

  • AMP — We will continue to support Web configurations that previously had Accelerated Mobile Pages (AMP) enabled, but AMP is not supported for new configurations.

  • Secure bridge — For Web SDK v1, we provided a workaround script for sites that were not fully HTTPS. This workaround was not required for non-HTTPS sites on Safari. Secure bridge is not supported for v2 integrations.

  • Safari versions older than 16 — Web SDK v1 supported Safari versions older than 16, which required an Apple Safari Web Push certificate in your Airship Web channel configuration. This is not supported for Web SDK v2 integrations.

    If your Web channel was 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.

Begin by configuring your site in the dashboard. Navigation to the settings differs depending on whether you have App or Web ScenesA single or multi-screen in-app experience cached on users’ devices and displayed when users meet certain conditions in your app or website, such as viewing a particular screen or when a Custom Event occurs. They can be presented in fullscreen, modal, or embedded format using the default swipe/click mode or as a Story. Scenes can also contain survey questions. enabled for your project.

 Warning

The downloadable SDK bundle is for Web SDK v2 only. If you need to update your web push default values (Title, Action, Icon URL) and do not need to migrate to v2, do not make changes to your Web channel configuration. Instead, directly edit the content from your snippet.html that you added to each page of your website.

  1. Go to Settings.
  2. (If you do not have Scenes or have App Scenes only) Under Channels, select Web.
  3. (If you have both App and Web Scenes) Under Channels, select Mobile App & Web. Then, under Platforms, select Web.
  4. Configure default values for each field. The preview updates as you enter information. You can override your default values on a per message basis via the dashboard or API.
    FieldDescriptionSteps
    Default TitleThe bolded title that appears above the message body, typically your brand nameEnter text.
    Default Action URLThe URL that opens when a user clicks your message, typically your brand's homepage URLEnter a publicly accessible URL.
    Default Icon URLThe path to the image that will appear in your web push notifications. If you have CDN enabled, you also have the option to upload an icon. See also Web icon in our Media guidelines documentation.Enter a publicly accessible URL or select Upload icon and select an image file.
  5. Select Save. The button will be labeled Update if you are editing a previous configuration.
  6. Select Download SDK Bundle and save the zip file.
  7. 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 to Web Pages

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 is a Promise which resolves to the SDK object:

const sdk = await UA
const {channelId} = await sdk.create()
console.log("Channel ID: %s", channelId)
 Note

Our documentation uses the async/await syntax for promises, which may not be available to you depending on your environment. If this is the case, you may use the classic then syntax, such as:

UA.then(function (sdk) {
   sdk.create().then(function (result) {
      console.log("Channel ID: %s", result.channelId)
   })
})

iOS and iPadOS Safari

Apple added Safari support for web push in iOS and iPadOS 16.4. To use web notifications and Scenes 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 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 is true if the SDK can load and track events; web push support is not considered
  • sdk.isWebPushSupported is true if the browser is supported and supports web push; it does not consider if the current context is supported (such as requiring it be added to the home screen on iOS)
  • sdk.isAllowedPushRegistrationContext is true if the browser is currently in an allowed registration context; note this does not otherwise check for browser features, so should only be checked after an sdk.isWebPushSupported check
  • sdk.canRegister() is a comprehensive check against all checks required for web push registration, and returns a promise which resolves to true if:
    • the browser supports web push
    • the page is a secure context
    • the browser is in an allowable context (such as being saved to the home screen on iOS)
    • push permission has not already been denied

When registering for web push, if isSupported is true and the value returned from canRegister() resolves to 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

const canRegister = await sdk.canRegister()
if (sdk.isSupported && !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.

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.

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 notification via the dashboard, see:

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 web push 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 the following in the JavaScript console:
const sdk = await UA
const channelId = await sdk.channel.id()
console.log("Channel ID: %s", channelId)
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 web 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.

Creating a Channel

You may create a channel by using the Airship SDK’s create method; using this method will make the current browser known to Airship, and allow you to use the SDK features.

const sdk = await UA
await sdk.create()

Registering for Push Notifications

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 if the browser is in an unsupported context.
 Note

A request to register for push notifications must happen as the result of a user interaction, otherwise the registration will be rejected by the browser without prompting the user.

Example registration
const sdk = await UA

// now that the SDK is available, add a registration button to the DOM
const button = document.createElement('button')
button.innerHTML = "Register for Notifications"
button.onclick = async (el) => {
   await sdk.register()
}
document.body.append(button)

Checking Browser Capabilities

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

  • sdk.isSupported is true if the SDK can load and track events; web push support is not considered
  • sdk.isWebPushSupported is true if the browser is supported and supports web push; it does not consider if the current context is supported (such as requiring it be added to the home screen on iOS)
  • sdk.isAllowedPushRegistrationContext is true if the browser is currently in an allowed registration context; note this does not otherwise check for browser features, so should only be checked after an sdk.isWebPushSupported check
  • sdk.canRegister() is a comprehensive check against all checks required for web push registration, and returns a promise that resolves to true if:
    • the browser supports web push
    • the page is a secure context
    • the browser is in an allowable context (such as being saved to the home screen on iOS)
    • push permission has not already been denied

Using these methods may be important if you wish to support Safari on iOS or iPad OS, as those have special requirements before push notification registration is allowed:

Checking for Push Notification Registration Support
const permission = await sdk.getNotificationPermission()
if (permission === 'granted') {
  await sdk.register()
}

if (permission === 'denied') {
   // user has denied notifications at the browser level, and opt-in is not
   // possible without the user changing their browser settings
} else if (sdk.isWebPushSupported && !sdk.isAllowedPushRegistrationContext) {
  // prompt user to add the website to their home screen
} else if (await sdk.canRegister()) {
  // is in an allowed context; prompt the user to opt into push notifications
}

Channel Object

The property sdk.channel returns the channel interface for the current browser. It contains methods for retrieving or setting information on the channel.

Example
const sdk = await UA
// the current channel id, a string. will be `null` if no channel exists
const channelId = await sdk.channel.id()
// the current opted-in status, a boolean
const optedIn = await sdk.channel.optedIn()
// opt out the channel for push notifications
const optedIn = await sdk.channel.optOut()

Event Listeners

The channel interface fires a channel event when a channel is loaded or registered.

 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.

const sdk = await UA
sdk.channel.addEventListener('channel', ev => {
   console.log('channel id:', ev.detail.id)
}, { once: true })

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

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