Web SDK setup
Web Push Notifications are a great way for engaging and retaining users. In this setup guide, we’ll show you how to quickly and easily add web push notifications to your website for free using OneSignal.
These instructions are for adding the OneSignal Web SDK to your website. See our WordPress Setup or Shopify App Setup if using those platforms.
Setting up push notifications for your website
Web push notifications empower you to deliver real-time updates, reminders, and personalized messages directly to your users, improving the overall user experience and stickiness of your site. By integrating OneSignal’s SDK with your site, you can take advantage of Chrome, Firefox, Edge, Safari and other supported browser's push notification capabilities while only writing code once. This guide will walk you through the steps to configure push notifications for your website and work across desktop and mobile.
Requirements
- HTTPS website. Web push does not work on HTTP websites or using incognito or private browser modes.
- Access to your server. Web push requires a service worker to be uploaded or added to your site.
- A single origin. For security reasons, web push follows the Same-origin policy. If you have multiple origins (domains/subdomains), you will need multiple OneSignal apps (one per origin). To comply with this browser limitation, you can either:
- Choose a single origin and redirect traffic to it for subscription.
- Set up multiple OneSignal apps for each origin.
Add your team!
If your team already created an account with OneSignal, ask to be invited as an admin role so you can setup the app. Otherwise, sign up for a free account at onesignal.com to get started!
Configure your OneSignal app and platform
Within your OneSignal app, navigate to Settings > Platforms > Web and open/activate the web settings.
Most of these settings are explained in the Web push setup guide, but a few items to double check under site setup:
Site URL
This must be the exact origin (URL) of your site. For example, if your site is https://yourdomain.com
, don’t use https://www.yourdomain.com
. If you go to a page of your website where you want the prompt to display, copy past the URL into this field to get the site origin. Follow the Same-origin policy for more details. If you have multiple origins, you will need multiple OneSignal apps (one per origin). To comply with this browser limitation, you can either:
- Choose a single origin and redirect traffic to it for push subscription.
- Set up multiple OneSignal apps for each origin.
Local testing
Our web SDK can be tested on localhost environments. If you are testing on localhost, we recommend setting up a different OneSignal app other than your production app.
Details on localhost testing (click to expand)
You can test OneSignal on your local environment by specifying a common localhost URL like the following into your Site URL:
http://localhost
orhttp://localhost:3000
http://127.0.0.1
orhttp://127.0.0.1:5000
If your localhost is using HTTP, then select Treat HTTP localhost as HTTPS for testing. Google Chrome treats http://localhost
and http://127.0.0.1
as secure origins, allowing HTTPS integrations even on HTTP. This is also why you cannot test other non-standard localhost origins. Please note that these HTTP origins are the only exceptions, and HTTP production sites will not have a working HTTPS integration.
HTTPS Localhost Example Code
If your local testing environment uses HTTPS, add allowLocalhostAsSecureOrigin: true,
to your OneSignal init
options.
Additionally, if you're testing localhost on HTTPS with a self-signed certificate, you may have to ask Chrome to ignore invalid certificates for testing with: --allow-insecure-localhost
. Firefox and Safari provide built-in mechanisms to add exceptions for security certificates.
<script src="https://cdn.onesignal.com/sdks/web/v16/OneSignalSDK.page.js" defer></script>
<script>
window.OneSignalDeferred = window.OneSignalDeferred || [];
OneSignalDeferred.push(function(OneSignal) {
OneSignal.init({
appId: "YOUR_OS_APP_ID",
allowLocalhostAsSecureOrigin: true,
});
});
</script>
Advanced settings
Before adding our SDK to your site, there are a couple configurations you may need to set.
Webhooks
Our web SDK provides the ability to POST
certain web push events to a URL of your choosing. See Web Push Webhooks for details.
Service workers
On the next step of web push configuration, you will be provided the OneSignalSDKWorker.js
service worker file.
Our web SDK defaults to looking for this file in the root of your site. If you want to change our service worker file location, name, scope and/or use multiple service workers on your site, this is where you can update those settings.
If you don't have any other service workers on your site and don't plan to add any other service workers. You can simply upload the .js
file to the root directory of your server and continue.
If you do want to update these settings, then simply toggle on this option.
- Path to service worker files is path to the directory you will put these files.
- Main and Updater service worker filenames can just be
OneSignalSDKWorker.js
or if you want to rename this file. Must use.js
file extension. - Service worker registration scope are the pages this file can work on. For push notifications, this doesn't matter and was originally designed for cases where you want to add more functionality to the service worker file. You should set this as the same path as your location.
With this example, as long as the service worker file is publicly accessible at https://yourdomain.com/push/onesignal/OneSignalSDKWorker.js
then you should be setup correctly.
For more details, see OneSignal Service Worker.
Click behavior & persistence
OneSignal supports several different possible browser behaviors when users receive and click your notifications. These options can always be updated at a later time.
If you update these settings, make sure to click Save all the way through and wait several minutes for the new settings to update on your site. Only subscribers that return to your site after these changes will see them. So return to your site and if you use a browser that supports these options, you should see the effects take place.
Details on click behavior (click to expand)
Control how users navigate to the URL you set when clicking the notification. See URLs, Links and Deep Links for details on adding links to your notifications.
If users do not have your site open on any browser tabs, and click on a notification that takes them to your site, the browser will open a new tab and navigate to the notification's URL.
If users have your site open on one or more browser tabs, and click on a notification that takes them to your site, there are several possible ways the browser can behave that you can configure:
- Exact Navigate (default) - If the notification's exact URL (e.g.
example.com/product
) matches a tab that the browser already has open, the browser will navigate to the notification's URL in that tab. - Origin Navigate - If the notification's origin (e.g.
example.com
) matches a tab that the browser already has open, the browser will navigate to the notification's URL in that tab. - Exact Focus - If the notification's exact URL (e.g.
example.com/product
) matches a tab that the browser already has open, the browser will focus on that tab, but not refresh the page. - Origin Focus - If the notification's origin (e.g.
example.com
) matches a tab that the browser already has open, the browser will focus on that tab, but not refresh the page.
Details on push persistence (click to expand)
The default web push behavior is they pop-up on the device for roughly 5 seconds before they are moved to the Notification Center where they are kept for about 1 week before being removed by the operating system.
Some devices and versions of Chrome and Edge allow you to persist notifications for longer on the screen. This means the notification will stay on the screen until the user interacts with it. This might annoy your users and is not recommended. Also, if you enable persistence it will affect how notifications appear to subscribers by reducing character count and may affect how images and buttons are displayed.
When changing them, they will go into effect only for subscribers that visit the site with the updated settings. If you do not see these options change, you will either need to wait
Safari certificate (Optional)
OneSignal automatically provides the necessary certificates to work with Safari browsers at no additional cost. If you already have your own Safari Web Push Certificates, toggle on this option to upload your Safari Web .p12 Push Certificate
and password.
Click Save to continue.
Upload service worker file
As discussed above in the Advanced settings > Service workers section, you can now click Download OneSignal SDK file which contains the OneSignalSDKWorker.js
Service Worker file.
If you haven't uploaded this to your server already, you will need to place it either in your site's top-level root or in a subdirectory. This file is only one line of code, so you can either:
Option 1. Create the file on your server and copy the code
-
Create a new file called
OneSignalSDKWorker.js
and make it public. -
Copy-paste the following import statement into the file:
importScripts("https://cdn.onesignal.com/sdks/web/v16/OneSignalSDK.sw.js");
Option 2. Download zip folder and upload
-
Click Download OneSignal SDK files (you can also download the file here).
-
Unzip the download. There should be a single file you need to host.
Once the file is on your server, check the following to make sure it works:
1. Verify the location
Make sure the file is located in the same "Path to service worker files" as set in Advanced settings > Service workers. If you did not update these settings, then you should have put the file in your root. For example:
https://yourdomain.com/OneSignalSDKWorker.js
https://yourdomain.com/some-subdirectory/OneSignalSDKWorker.js
2. It must be publicly accessible on your origin
The OneSignalSDKWorker.js
file must be publicly accessible and available on your origin. It cannot be hosted via a CDN or placed on a different origin with redirect.
When you visit the URL to the file, you should see the code.
3. It must be served with a content-type: application/javascript
This is a javascript file and needs to be served as such. It cannot have a content-type of text/html.
OneSignal's service worker docs
If you have additional questions or migrating to OneSignal from a different web push provider, it is recommended to review our OneSignal Service Worker docs.
Add code to your site
You should now be all set to add our SDK to your site. Our JavaScript SDK code provided should work on any site, but if your site is setup using Angular, React JS, or Vue JS then follow these links.
To initialize OneSignal on your site with our JavaScript SDK, copy/paste the provided code into your website's <head>
tags. Our dashboard will provide the following code but includes your OneSignal app ID.
<script src="https://cdn.onesignal.com/sdks/web/v16/OneSignalSDK.page.js" defer></script>
<script>
window.OneSignalDeferred = window.OneSignalDeferred || [];
OneSignalDeferred.push(async function(OneSignal) {
await OneSignal.init({
appId: "YOUR_ONESIGNAL_APP_ID",
});
});
</script>
iOS web push support
Apple started supporting web push notifications on iPhones and iPads running iOS 16.4+. Unlike Android devices where web push just "works" as long as visited on a supported browser, Apple added a few more requirements for web push to work on iPhones and iPads:
- To set this up, you need to add/update your Web Application Manifest.
- Your users must add your site to their home screen. See Getting Your Audience to "Add to Home Screen".
Full setup details, testing and troubleshooting can be found in Mobile Web Push for iOS/iPadOS.
Testing
Go to your website. Make sure you are not in incognito or private browser modes and using a browser that supports web push notifications.
You should be prompted to subscribe to push notifications based on the prompt settings you setup. See Web Permission Prompts if you have not set these up yet. Click "Allow" on the native browser prompt to subscribe to push.
Check your OneSignal Dashboard Audience > Subscriptions to see your Subscription and click the options button on the left to set yourself as a Test Subscription.
Troubleshooting
If running into issues, see our Web SDK troubleshooting guide for common resolutions.
If stuck, contact support directly or email [email protected] for help.
For faster assistance, please provide:
- Your OneSignal App ID
- The website with the OneSignal code
- Steps to reproduce
Users & subscriptions
Required if using integrations.
Recommended for messaging across multiple channels (push, email, sms).
If you need user consent before tracking their data. OneSignal provides user consent methods to help delay initialization of our SDK until consent is provided. See Handling Personal Data for details.
External ID & aliases
When a user subscribes to your website and/or later clears browser data and returns to your site on the same device, a Subscription and a User is created within the OneSignal app.
You can identify that user across multiple subscriptions by setting the External ID property. The External ID should be distinct user ID representing a single user. We recommend using the same user ID as in your Integrations or main analytics tool.
When you authenticate users in your app, call our login
method at any time to link this subscription to a user.
OneSignalDeferred.push(async function(OneSignal) {
await OneSignal.login("external_id");
});
//Example combining with push subscription change event
function pushSubscriptionChangeListener(event) {
if (event.current.token) {
console.log(`The push subscription has received a token!`);
//this is a good place to call OneSignal.login and pass in your user ID
OneSignal.login("external_id");
}
}
OneSignalDeferred.push(function(OneSignal) {
OneSignal.User.PushSubscription.addEventListener("change", pushSubscriptionChangeListener);
});
External ID & custom aliases
If your users have multiple user IDs, we do support additional custom Aliases. However, you should still always set the External ID as this is the main alias we use to identify users. See Users for details.
Add email and phone number subscriptions
Recommended if using email and SMS messaging.
Like push subscriptions, email addresses and phone numbers each are a new subscription within OneSignal. Your email and sms subscriptions will be tied to the same user if created using our SDK or if you setting the External ID. You can Import your current user data and use our APIs and/or SDK methods to capture new email addresses and phone numbers when provided to you by your users.
// Pass in email provided by customer
OneSignal.User.addEmail("[email protected]");
// Pass in phone number provided by customer
OneSignal.User.addSms("+15558675309");
Users & subscriptions
See Users and Subscriptions for more details.
Add Data Tags
Tags are custom key : value
pairs of String data used for tracking any custom user events and properties. Setting tags is required for more complex Segments and Message Personalization.
For event triggered messages, use tags with Time Operators to note the date and time the event is/occurred and setup automations for sending to those users. See Abandoned Cart Example for details.
// Example adding single tag
OneSignal.User.addTag('tag_key', 'tag_value');
// Example adding multiple tags
OneSignal.User.addTags({
KEY_01: "VALUE_01",
KEY_02: "VALUE_02",
KEY_03: "VALUE_03"
});
Data tags
If you want to store custom data within OneSignal for segmentation, message personalization, and event triggered automation, see Tags for details.
Importing users and subscriptions
If you have a list of user data from a previous source, you can import it into OneSignal following our Import guides.
Basic SDK setup complete!
For details on the above methods and other methods available, see our Web SDK reference.
Updated 30 days ago