Web Push Examples
Commonly Asked Examples For Web Push
This guide shares commonly asked for code examples for theOneSignal Web Push SDK methods. Such as:
- Adding A Prompt Delay
- Location Tracking
- Delay Initialization Until Consent Provided For Data Privacy
Custom Code Initialization
How to initialize OneSignal with Custom Code Setup
For Custom Code Setup only
Skip this section if using the Typical Setup or Site Builder (Wordpress) setup.
IMPORTANT Setup Instructions
1. Do not host OneSignalSDK.js
yourself, use our CDN URL instead.
2 Add your appid
which is found in Keys & IDs.
3. Make sure your URL is spelled correctly. Do not include www
in the URL if your site does not use it. Also do include www
in the URL if your site does use it.
Custom Code HTTPS Initialization
For HTTPS sites.
Calling OneSignal.showNativePrompt(); will show the native browser prompt right away.
<head>
<script src="https://cdn.onesignal.com/sdks/OneSignalSDK.js" async=""></script>
<script>
OneSignal = window.OneSignal || [];
OneSignal.push(function() {
OneSignal.init({
appId: "YOUR_APP_ID",
notifyButton: {
enable: true,
},
});
OneSignal.showNativePrompt();
});
</script>
</head>
Custom Code HTTP Initialization
For HTTP sites, or HTTPS sites using For HTTP:
<head>
<script src="https://cdn.onesignal.com/sdks/OneSignalSDK.js" async=""></script>
<script>
OneSignal = window.OneSignal || [];
OneSignal.push(function() {
OneSignal.init({
appId: "YOUR_APP_ID",
subdomainName:"YOUR_LABEL"/* The label for your site that you added in Site Setup mylabel.os.tc */
notifyButton: {
enable: true,
},
});
});
</script>
</head>
HTTP SETUP For HTTPS Site
Used on HTTPS sites that require the HTTP setup
subdomainName
is the label you have chosen in Site Setup
<head>
<script src="https://cdn.onesignal.com/sdks/OneSignalSDK.js" async=""></script>
<script>
OneSignal = window.OneSignal || [];
OneSignal.push(function() {
OneSignal.init({
appId: "YOUR_APP_ID",
subdomainName:"YOUR_LABEL"/* The label for your site that you added in Site Setup mylabel.os.tc */
notifyButton: {
enable: true,
},
});
});
</script>
</head>
HTTPS Setup for resubscribing users
The below setups are mainly for silently importing users into OneSignal or handle automatically re-subscribing users when they have already subscribed to the site and deleted their browser cookies.
This can be done with Typical Setup or Custom Code Setup.
Using requiresUserPrivacyConsent
For Typical Setup and Custom Code Setup
This will prevent our sdk from being initialized until your receive consent from your users. In which case you can then call the provideUserConsent method to initialize the SDK.
<head>
<script src="https://cdn.onesignal.com/sdks/OneSignalSDK.js" async=""></script>
<script>
OneSignal = window.OneSignal || [];
OneSignal.push(function() {
OneSignal.init({
appId: "YOUR_APP_ID",
requiresUserPrivacyConsent: true,
autoResubscribe: false,
notifyButton: {
enable: true,
},
});
});
</script>
</head>
<head>
<script src="https://cdn.onesignal.com/sdks/OneSignalSDK.js" async=""></script>
<script>
var OneSignal = window.OneSignal || [];
OneSignal.push(function() {
OneSignal.init({
appId: "YOUR_APP_ID",
requiresUserPrivacyConsent: true,
subdomainName:"YOUR_LABEL"/* The label for your site that you added in Site Setup mylabel.os.tc */
notifyButton: {
enable: true,
},
});
});
</script>
</head>
Welcome Notifications
Welcome notifications are a great on-boarding experience for users who have just signed up to your site, because they give users immediate feedback on what the experience of receiving web push notifications from your site will be like.
If welcome notifications are enabled, as soon as a user subscribes to push notifications on your site, they will receive a notification thanking them for joining.
Typical Setup Welcome Notification
See Step 4. Welcome Notification.
Make sure to press save twice. Once on the setup prompt and again on the Typical setup config page at the bottom.
Wordpress Welcome Notification
This is done under the "Welcome Notification Settings"
Custom Code Welcome Notification
Use the welcomeNotification
parameter in your init() options. The url
parameter is, by default, set to a special value that, on Chrome and Firefox, disables the notification from opening a separate webpage. By default, Safari must open a webpage and it will default to your site's URL. You may optionally set url
so the notification opens a separate URL (on Chrome, Safari, and Firefox).
Showing a Welcome Notification
// Other init Options
welcomeNotification: {
"title": "My Custom Title",
"message": "Thanks for subscribing!",
// "url": "" /* Leave commented for the notification to not open a window on Chrome and Firefox (on Safari, it opens to your webpage) */
}
<head>
<link rel="manifest" href="/manifest.json" />
<script src="https://cdn.onesignal.com/sdks/OneSignalSDK.js" async=""></script>
<script>
var OneSignal = window.OneSignal || [];
OneSignal.push(function() {
OneSignal.init({
appId: "YOUR_APP_ID",
autoResubscribe: true,
notifyButton: {
enable: true,
},
welcomeNotification: {
"title": "My Custom Title",
"message": "Thanks for subscribing!",
// "url": "" /* Leave commented for the notification to not open a window on Chrome and Firefox (on Safari, it opens to your webpage) */
}
});
OneSignal.showNativePrompt();
});
</script>
</head>
<head>
<script src="https://cdn.onesignal.com/sdks/OneSignalSDK.js" async=""></script>
<script>
var OneSignal = window.OneSignal || [];
OneSignal.push(function() {
OneSignal.init({
appId: "YOUR_APP_ID",
subdomainName:"YOUR_LABEL"/* The label for your site that you added in Site Setup mylabel.os.tc */
notifyButton: {
enable: true,
},
welcomeNotification: {
"title": "My Custom Title",
"message": "Thanks for subscribing!",
// "url": "" /* Leave commented for the notification to not open a window on Chrome and Firefox (on Safari, it opens to your webpage) */
}
});
});
</script>
</head>
Disabling Welcome Notifications
// Other init options
welcomeNotification: {
disable: true
}
<head>
<link rel="manifest" href="/manifest.json" />
<script src="https://cdn.onesignal.com/sdks/OneSignalSDK.js" async=""></script>
<script>
var OneSignal = window.OneSignal || [];
OneSignal.push(function() {
OneSignal.init({
appId: "YOUR_APP_ID",
autoResubscribe: true,
notifyButton: {
enable: true,
},
welcomeNotification: {
disable: true
}
});
OneSignal.showNativePrompt();
});
</script>
</head>
<head>
<script src="https://cdn.onesignal.com/sdks/OneSignalSDK.js" async=""></script>
<script>
var OneSignal = window.OneSignal || [];
OneSignal.push(function() {
OneSignal.init({
appId: "YOUR_APP_ID",
subdomainName:"YOUR_LABEL"/* The label for your site that you added in Site Setup mylabel.os.tc */
notifyButton: {
enable: true,
},
welcomeNotification: {
disable: true
}
});
});
</script>
</head>
Custom Link Prompt
Custom Code
Trigger Custom Link Prompt
Instead of using our pre-built templates, you may also choose to create your own Prompt with a link.
HTTPS - this link prompts a browser Permission Request when clicked.
HTTP - this link opens the HTTP Pop-Up Prompt.
We highly recommend only showing this custom Prompt and link if the user is unsubscribed. Below is an example of code that does this:
<body>
<a href="#" id="my-notification-button" style="display: none;">Subscribe to Notifications</a>
<script>
function onManageWebPushSubscriptionButtonClicked(event) {
getSubscriptionState().then(function(state) {
if (state.isPushEnabled) {
/* Subscribed, opt them out */
OneSignal.setSubscription(false);
} else {
if (state.isOptedOut) {
/* Opted out, opt them back in */
OneSignal.setSubscription(true);
} else {
/* Unsubscribed, subscribe them */
OneSignal.registerForPushNotifications();
}
}
});
event.preventDefault();
}
function updateMangeWebPushSubscriptionButton(buttonSelector) {
var hideWhenSubscribed = false;
var subscribeText = "Subscribe to Notifications";
var unsubscribeText = "Unsubscribe from Notifications";
getSubscriptionState().then(function(state) {
var buttonText = !state.isPushEnabled || state.isOptedOut ? subscribeText : unsubscribeText;
var element = document.querySelector(buttonSelector);
if (element === null) {
return;
}
element.removeEventListener('click', onManageWebPushSubscriptionButtonClicked);
element.addEventListener('click', onManageWebPushSubscriptionButtonClicked);
element.textContent = buttonText;
if (hideWhenSubscribed && state.isPushEnabled) {
element.style.display = "none";
} else {
element.style.display = "";
}
});
}
function getSubscriptionState() {
return Promise.all([
OneSignal.isPushNotificationsEnabled(),
OneSignal.isOptedOut()
]).then(function(result) {
var isPushEnabled = result[0];
var isOptedOut = result[1];
return {
isPushEnabled: isPushEnabled,
isOptedOut: isOptedOut
};
});
}
var OneSignal = OneSignal || [];
var buttonSelector = "#my-notification-button";
/* This example assumes you've already initialized OneSignal */
OneSignal.push(function() {
// If we're on an unsupported browser, do nothing
if (!OneSignal.isPushNotificationsSupported()) {
return;
}
updateMangeWebPushSubscriptionButton(buttonSelector);
OneSignal.on("subscriptionChange", function(isSubscribed) {
/* If the user's subscription state changes during the page's session, update the button text */
updateMangeWebPushSubscriptionButton(buttonSelector);
});
});
</script>
</body>
Prompt Behavior
Add Delay to Prompt
Wordpress Users please see how do I delay prompting on Wordpress docs
Delay Prompting for X amount of seconds or X page views
Typical Setup & Custom Code Setup
The following code example will delay the slidedown prompt by 20 seconds on the 3rd visit. If you want to trigger the native prompt instead of the slidedown, simply replace slidedown
with native
.
<script src="https://cdn.onesignal.com/sdks/OneSignalSDK.js" async=""></script>
<script>
var OneSignal = window.OneSignal || [];
/* Why use .push? See: http://stackoverflow.com/a/38466780/555547 */
OneSignal.push(function() {
OneSignal.init({
appId: "YOUR_APP_ID",
promptOptions: {
slidedown: {
enabled: true,
autoPrompt: true,
timeDelay: 20,
pageViews: 3
}
}
});
</script>
<script src="https://cdn.onesignal.com/sdks/OneSignalSDK.js" async=""></script>
<script>
var OneSignal = window.OneSignal || [];
OneSignal.push(function() {
OneSignal.init({
appId: "YOUR_APP_ID",
subdomainName: "your_label", /* The label for your site that you added in Site Setup mylabel.os.tc */
promptOptions: {
slidedown: {
enabled: true,
autoPrompt: true,
timeDelay: 20,
pageViews: 3
}
}
});
</script>
Add Location Tracking
HTTPS SETUP Location Tracking
Location Tracking Only Available on HTTPS
<body>
<p><button onclick="geoFindMe()">Show my location</button></p>
<div id="out"></div>
<script>
var output = document.getElementById("out");
function geoFindMe() {
if (!navigator.geolocation) {
output.innerHTML = "<p>Geolocation is not supported by your browser</p>";
return;
}
output.innerHTML = "<p>Locating…</p>";
navigator.geolocation.getCurrentPosition(success, error);
}
function success(position) {
var latitude = position.coords.latitude;
var longitude = position.coords.longitude;
output.innerHTML = '<p>Latitude is ' + latitude + '° <br>Longitude is ' + longitude + '°</p>';
OneSignal.push(function() {
OneSignal.sendTags({
latitude: latitude,
long: longitude
});
});
var img = new Image();
img.src = "https://maps.googleapis.com/maps/api/staticmap?center=" + latitude + "," + longitude + "&zoom=13&size=300x300&sensor=false";
output.appendChild(img);
}
function error() {
output.innerHTML = "Unable to retrieve your location";
}
</script>
</body>
OneSignal Files
Hosting Files from Subfolders
Custom Code - If the files are served with the HTTP header "Service-Worker-Allowed: /"
, please add this code before initializing the SDK
var OneSignal = OneSignal || [];
OneSignal.push(function() {
// Be sure to call this code *before* you initialize the web SDK
// This registers the workers at the root scope, which is allowed by the HTTP header "Service-Worker-Allowed: /"
OneSignal.SERVICE_WORKER_PARAM = { scope: '/' };
});
Custom Code - If the files are served from a subfolder, please add this code during the initialization options so our SDK knows where to find the workers:
// Do NOT call init() twice
OneSignal.push(["init", {
// Your other init options here
path: '/subfolder/', /* A trailing slash is required */
}]);
Notification Behavior
Notification Persistence
Firefox, Safari - notifications are automatically dismissed after a short amount of time.
Chrome (non-mobile) - notifications last indefinitely (displayed until the user interacts with it by dismissing it or clicking it). Add the persistNotification
parameter to your OneSignal init call to control whether a notification is displayed indefinitely or dismissed after 20 seconds.
persistNotification
defaults to true if unset. Set it to false to automatically dismiss the notification after 20 seconds (Chrome non-mobile only).
// Do NOT call init() twice
OneSignal.push(["init", {
// Your other init options here
persistNotification: false // Automatically dismiss the notification after ~20 seconds in non-mobile Chrome
}]);
Updated over 2 years ago