OneSignal Help & Documentation

Welcome to the OneSignal New IA developer hub. You'll find comprehensive guides and documentation to help you start working with OneSignal New IA as quickly as possible, as well as support if you get stuck. Let's jump right in!

Get Started    Discussions

Web Push Examples

Custom Code Examples For Web Push

Advanced Topic

This guide shares example code to setup OneSignal prompts, welcome notifications and other Web Push SDK methods.

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. Reference manifest.json in your <head> just like shown below.

  • An error will occur if manifest.json is referenced in <body>.
  • <link rel="manifest" href="/manifest.json"> must appear before any other <link rel="manifest" ...> in <head>, otherwise it will not be found

2. *Do not host OneSignalSDK.js yourself, use our CDN URL instead.

3 Add your appid which is found in Keys & IDs.

4. 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 us it.

Custom Code HTTPS Initialization

For HTTPS sites.

Calling OneSignal.registerForPushNotifications(); will show the native browser prompt right away.

<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",
      autoRegister: false,
      notifyButton: {
        enable: true,
      },
    });
    OneSignal.registerForPushNotifications();
  });
</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='async'></script>
  <script>
    var OneSignal = window.OneSignal || [];
    OneSignal.push(["init", {
      appId: "YOUR_APP_ID",
      autoRegister: false, /* Set to true to automatically prompt visitors */
      notifyButton: {
          enable: true /* Set to false to hide */
      }
    }]);
  </script>
</head>

Custom Code HTTP on HTTPS Sites

If your site is built with technology that uses HTTPS but requires our HTTP setup, see HTTP Setup on HTTPS sites.


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 requires the Custom Code Setup.

Option 1: Show Native Browser Prompt
To show the native browser prompt and automatically resubscribe users upon returning to site use above custom code HTTPS initialization with the registerForPushNotifications(); method.

Option 2: Show the OneSignal Slide Prompt
If you want show the slide prompt and automatically resubscribe users upon return

<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",
        autoRegister: false,
        notifyButton: {
          enable: true,
        },
        promptOptions: {
          /* actionMessage limited to 90 characters */
          actionMessage: "We'd like to show you notifications for the latest news and updates.",
          /* acceptButtonText limited to 15 characters */
          acceptButtonText: "ALLOW",
          /* cancelButtonText limited to 15 characters */
          cancelButtonText: "NO THANKS"
        }
      });
      if (Notification.permission === "granted") {
        // Automatically subscribe user if deleted cookies and browser shows "Allow"
        OneSignal.registerForPushNotifications();
      } else {
        OneSignal.showHttpPrompt();
      }
    });
  </script>
</head>

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.

HTTPS Initialization with requiresUserPrivacyConsent

<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",
        requiresUserPrivacyConsent: true,
        autoRegister: false,
        notifyButton: {
          enable: true,
        },
      });
    });
  </script>
</head>

HTTP Initialization with requiresUserPrivacyConsent

<head>
  <script src="https://cdn.onesignal.com/sdks/OneSignalSDK.js" async='async'></script>
  <script>
    var OneSignal = window.OneSignal || [];
    OneSignal.push(["init", {
      appId: "YOUR_APP_ID",
      requiresUserPrivacyConsent: true,
      autoRegister: false,
      notifyButton: {
          enable: true /* Set to false to hide */
      }
    }]);
  </script>
</head>

Welcome Notifications

This is the first notification users receive after subscribing.

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

Customize or disable the automatic 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

// Do NOT call init() twice
OneSignal.push(["init", {
    /* Your other init options here */
    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) */
    }
}]);

Disabling Welcome Notifications

// Do NOT call init() twice
OneSignal.push(["init", {
    welcomeNotification: {
        disable: true
    }
}]);

Custom Code HTTPS SETUP Welcome Notification

<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(["init", {
      appId: "YOUR_APP_ID",
      autoRegister: false,
      notifyButton: {
        enable: true /* Set to false to hide */
      },
      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>

Custom Code HTTP SETUP Welcome Notification

<head>
  <script src="https://cdn.onesignal.com/sdks/OneSignalSDK.js" async='async'></script>
  <script>
    var OneSignal = window.OneSignal || [];
    OneSignal.push(["init", {
      appId: "YOUR_APP_ID",
      autoRegister: false, /* Set to true to automatically prompt visitors */
      httpPermissionRequest: {
        enable: true
      },
      notifyButton: {
          enable: true /* Set to false to hide */
      },
      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>

Web Push Prompts

To create the most compelling messages for why users should subscribe to your push notifications, you need to customize your Prompt content. You may enter text in your own language, but please note all fields are limited in length (usually to one line of text). If you have chosen to implement a Custom Link, you may customize it any way you like.

To learn about Web Push Prompts, including an overview and best practices, first read our feature overview of Prompts & Permission Requests.

Built-In Prompts Overview

OneSignal offers the following built-in Prompt designs:

Prompt
Triggering Notes
Customizability Notes

Typical Sites - enabled by default.

Color and text

Wordpress - enabled by default.

Icon, text, and buttons

HTTP only - Triggered when other prompts are clicked on.

Icon, text, and buttons

Custom Code - Supports implementing custom prompt

Text

Subscription Bell

The subscription bell is a small widget that resides in the bottom corner of your site, which users can click to bring up the Permission Request for your site. It is designed to be small enough that you may keep it on your site at all times, and does not require users to dismiss it.

This section shows you how to trigger and customize the Subscription Bell. If you want to learn more about asking for push notification permissions, go here.

Typical Setup

See Step 3 Permission Prompt Setup

Wordpress

Trigger/Show Subscription Bell

Custom Code

Enabled through the example code we provide in Custom Code Setup.
Show: notifyButton: { enable: true }
Don't Show: notifyButton: { enable: false }

We do not currently support a way to manually show or hide the subscription bell.

Customize Subscription Bell

Custom Code

The colors and text of the Subscription Bell can be customized, however the icon itself cannot.

Custom Code - Use the notifyButton parameter in your web SDK initialization options.

// Do NOT call init() twice
OneSignal.push(["init", {
    /* Your other init options here */
    notifyButton: {
        enable: true, /* Required to use the Subscription Bell */
        size: 'medium', /* One of 'small', 'medium', or 'large' */
        theme: 'default', /* One of 'default' (red-white) or 'inverse" (white-red) */
        position: 'bottom-right', /* Either 'bottom-left' or 'bottom-right' */
        offset: {
            bottom: '0px',
            left: '0px', /* Only applied if bottom-left */
            right: '0px' /* Only applied if bottom-right */
        },
        prenotify: true, /* Show an icon with 1 unread message for first-time site visitors */
        showCredit: false, /* Hide the OneSignal logo */
        text: {
            'tip.state.unsubscribed': 'Subscribe to notifications',
            'tip.state.subscribed': "You're subscribed to notifications",
            'tip.state.blocked': "You've blocked notifications",
            'message.prenotify': 'Click to subscribe to notifications',
            'message.action.subscribed': "Thanks for subscribing!",
            'message.action.resubscribed': "You're subscribed to notifications",
            'message.action.unsubscribed': "You won't receive notifications again",
            'dialog.main.title': 'Manage Site Notifications',
            'dialog.main.button.subscribe': 'SUBSCRIBE',
            'dialog.main.button.unsubscribe': 'UNSUBSCRIBE',
            'dialog.blocked.title': 'Unblock Notifications',
            'dialog.blocked.message': "Follow these instructions to allow notifications:"
        }
    }
}]);

Customizing Subscription Bell Colors

Custom Code - You can override the theme's colors by entering your own. Values are strings which are then interpreted by CSS, so any CSS-valid color works as each value.
Examples: white, #FFFFFF, #FFF, rgb(255, 255, 255), rgba(255, 255, 255, 1.0), and transparent are all valid values.

// Do NOT call init() twice
OneSignal.push(["init", {
  // Your other init options here
  notifyButton: {
    enable: true, // Required to use the Subscription Bell
    // Your other Subscription Bell settings here
    colors: { // Customize the colors of the main button and dialog popup button
      'circle.background': 'rgb(84,110,123)',
      'circle.foreground': 'white',
      'badge.background': 'rgb(84,110,123)',
      'badge.foreground': 'white',
      'badge.bordercolor': 'white',
      'pulse.color': 'white',
      'dialog.button.background.hovering': 'rgb(77, 101, 113)',
      'dialog.button.background.active': 'rgb(70, 92, 103)',
      'dialog.button.background': 'rgb(84,110,123)',
      'dialog.button.foreground': 'white'
    },
  }
}]);

Hiding the Subscription Bell

Custom Code - To hide the subscription bell after a user subscribes or only show it on certain pages, be sure to return the value false or a Promise that resolves to the value false in the displayPredicate function during initialization. This function is evaluated before the subscription bell is shown. You may return any other value to show the subscription bell.

Here is an example hiding the subscription bell if the user is subscribed:

// Do NOT call init() twice
// This is just an example
OneSignal.push(["init", {
    /* Your other init options here */
    notifyButton: {
        /* Your other Subscription Bell settings here ... */
        enable: true,
        displayPredicate: function() {
            return OneSignal.isPushNotificationsEnabled()
                .then(function(isPushEnabled) {
                    /* The user is subscribed, so we want to return "false" to hide the Subscription Bell */
                    return !isPushEnabled;
                });
        },
    }
}]);

Full Code Example HTTPS SETUP Subscription Bell

<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(["init", {
      appId: "YOUR_APP_ID",
      autoRegister: false,
      notifyButton: {
        enable: true, /* Required to use the Subscription Bell */
      /* SUBSCRIPTION BELL CUSTOMIZATIONS START HERE */
        size: 'medium', /* One of 'small', 'medium', or 'large' */
        theme: 'default', /* One of 'default' (red-white) or 'inverse" (white-red) */
        position: 'bottom-right', /* Either 'bottom-left' or 'bottom-right' */
        offset: {
            bottom: '0px',
            left: '0px', /* Only applied if bottom-left */
            right: '0px' /* Only applied if bottom-right */
        },
        prenotify: true, /* Show an icon with 1 unread message for first-time site visitors */
        showCredit: false, /* Hide the OneSignal logo */
        text: {
            'tip.state.unsubscribed': 'Subscribe to notifications',
            'tip.state.subscribed': "You're subscribed to notifications",
            'tip.state.blocked': "You've blocked notifications",
            'message.prenotify': 'Click to subscribe to notifications',
            'message.action.subscribed': "Thanks for subscribing!",
            'message.action.resubscribed': "You're subscribed to notifications",
            'message.action.unsubscribed': "You won't receive notifications again",
            'dialog.main.title': 'Manage Site Notifications',
            'dialog.main.button.subscribe': 'SUBSCRIBE',
            'dialog.main.button.unsubscribe': 'UNSUBSCRIBE',
            'dialog.blocked.title': 'Unblock Notifications',
            'dialog.blocked.message': "Follow these instructions to allow notifications:"
        },
        colors: { // Customize the colors of the main button and dialog popup button
           'circle.background': 'rgb(84,110,123)',
           'circle.foreground': 'white',
           'badge.background': 'rgb(84,110,123)',
           'badge.foreground': 'white',
           'badge.bordercolor': 'white',
           'pulse.color': 'white',
           'dialog.button.background.hovering': 'rgb(77, 101, 113)',
           'dialog.button.background.active': 'rgb(70, 92, 103)',
           'dialog.button.background': 'rgb(84,110,123)',
           'dialog.button.foreground': 'white'
         },
        /* HIDE SUBSCRIPTION BELL WHEN USER SUBSCRIBED */
        displayPredicate: function() {
            return OneSignal.isPushNotificationsEnabled()
                .then(function(isPushEnabled) {
                    return !isPushEnabled;
                });
        }
      },
      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) */
      },
      promptOptions: {
        /* actionMessage limited to 90 characters */
        actionMessage: "We'd like to show you notifications for the latest news and updates.",
        /* acceptButtonText limited to 15 characters */
        acceptButtonText: "ALLOW",
        /* cancelButtonText limited to 15 characters */
        cancelButtonText: "NO THANKS"
      }
    }]);
    OneSignal.push(function() {
      OneSignal.showHttpPrompt();
    });
  </script>
</head>

Full Code Example HTTP SETUP Subscription Bell

<head>
  <script src="https://cdn.onesignal.com/sdks/OneSignalSDK.js" async='async'></script>
  <script>
    var OneSignal = window.OneSignal || [];
    OneSignal.push(["init", {
      appId: "YOUR_APP_ID",
      autoRegister: false, /* Set to true to automatically prompt visitors */
      httpPermissionRequest: {
        enable: true
      },
      notifyButton: {
        enable: true, /* Required to use the Subscription Bell */
      /* SUBSCRIPTION BELL CUSTOMIZATIONS START HERE */
        size: 'medium', /* One of 'small', 'medium', or 'large' */
        theme: 'default', /* One of 'default' (red-white) or 'inverse" (white-red) */
        position: 'bottom-right', /* Either 'bottom-left' or 'bottom-right' */
        offset: {
            bottom: '0px',
            left: '0px', /* Only applied if bottom-left */
            right: '0px' /* Only applied if bottom-right */
        },
        prenotify: true, /* Show an icon with 1 unread message for first-time site visitors */
        showCredit: false, /* Hide the OneSignal logo */
        text: {
            'tip.state.unsubscribed': 'Subscribe to notifications',
            'tip.state.subscribed': "You're subscribed to notifications",
            'tip.state.blocked': "You've blocked notifications",
            'message.prenotify': 'Click to subscribe to notifications',
            'message.action.subscribed': "Thanks for subscribing!",
            'message.action.resubscribed': "You're subscribed to notifications",
            'message.action.unsubscribed': "You won't receive notifications again",
            'dialog.main.title': 'Manage Site Notifications',
            'dialog.main.button.subscribe': 'SUBSCRIBE',
            'dialog.main.button.unsubscribe': 'UNSUBSCRIBE',
            'dialog.blocked.title': 'Unblock Notifications',
            'dialog.blocked.message': "Follow these instructions to allow notifications:"
        },
        colors: { // Customize the colors of the main button and dialog popup button
           'circle.background': 'rgb(84,110,123)',
           'circle.foreground': 'white',
           'badge.background': 'rgb(84,110,123)',
           'badge.foreground': 'white',
           'badge.bordercolor': 'white',
           'pulse.color': 'white',
           'dialog.button.background.hovering': 'rgb(77, 101, 113)',
           'dialog.button.background.active': 'rgb(70, 92, 103)',
           'dialog.button.background': 'rgb(84,110,123)',
           'dialog.button.foreground': 'white'
         },
        /* HIDE SUBSCRIPTION BELL WHEN USER SUBSCRIBED */
        displayPredicate: function() {
            return OneSignal.isPushNotificationsEnabled()
                .then(function(isPushEnabled) {
                    return !isPushEnabled;
                });
        }
      }
    }]);
  </script>
</head>

Slide Prompt

The Slide Prompt displays on top of your site, in the top center of the browser. This is the most attention-grabbing prompt offered by OneSignal.

This section shows you how to trigger and customize the Slide Prompt. If you want to learn more about asking for push notification permissions, go here.


Desktop (Firefox/Chrome) and Android Chrome versions of Slide Prompt

Typical Setup
See Step 3 Permission Prompt Setup

Wordpress

Custom Code

Trigger/Show Slide Prompt

Custom Code - Can be triggered any time via showHttpPrompt().

HTTPS - Set autoRegister: false
Can be triggered "automatically" if you call OneSignal.showHttpPrompt().
Note: the Slide Prompt cannot replace the browser's native prompt.
The browser's native permission prompt must ALWAYS be shown before the user can subscribe.

HTTP - Set autoRegister: true
Automatically triggered when a user arrives to your website if you set autoRegister: true during initialization. When users click 'Allow', this message triggers the browser's native permission prompt which must ALWAYS be shown before the user can subscribe.

FAQ

Why isn't my prompt showing up?

Customize Slide Prompt

Custom Code - You may customize the text in the Slide Prompt by including the contents in your initialization function:

// Do NOT call init() twice
OneSignal.push(["init", {
    // Your other init options here
    promptOptions: {
        /* These prompt options values configure both the HTTP prompt and the HTTP popup. */
        /* actionMessage limited to 90 characters */
        actionMessage: "We'd like to show you notifications for the latest news and updates.",
        /* acceptButtonText limited to 15 characters */
        acceptButtonText: "ALLOW",
        /* cancelButtonText limited to 15 characters */
        cancelButtonText: "NO THANKS"
    }
}]);

Customizing Icon

You may customize the website icon shown in the Slide Prompt by editing the Site Notification Icon URL in the Web Push Editor. Go to App Settings by clicking Configure next to the Google Chrome & Mozilla Firefox platform settings.

To edit the website icon, enter a link to an icon file that is at least 80x80 pixels (Recommended size is 192x192). The file must be .png or .jpg.

If you do not have a Default Notification Icon URL set, OneSignal will show a generic icon.

Full Code Example HTTPS Slide Prompt

<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(["init", {
      appId: "YOUR_APP_ID",
      autoRegister: false,
      notifyButton: {
        enable: true /* Set to false to hide */
      },
      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) */
      },
      promptOptions: {
        /* actionMessage limited to 90 characters */
        actionMessage: "We'd like to show you notifications for the latest news and updates.",
        /* acceptButtonText limited to 15 characters */
        acceptButtonText: "ALLOW",
        /* cancelButtonText limited to 15 characters */
        cancelButtonText: "NO THANKS"
      }
    }]);
    OneSignal.push(function() {
      OneSignal.showHttpPrompt();
    });
  </script>
</head>

Full Code Example HTTP Slide Prompt

<head>
  <script src="https://cdn.onesignal.com/sdks/OneSignalSDK.js" async='async'></script>
  <script>
    var OneSignal = window.OneSignal || [];
    OneSignal.push(["init", {
      appId: "YOUR_APP_ID",
      autoRegister: true, /* Set to true for HTTP Slide Prompt */
      httpPermissionRequest: {
        enable: true
      },
      notifyButton: {
          enable: true /* Set to false to hide */
      },
      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) */
      },
      promptOptions: {
        /* actionMessage limited to 90 characters */
        actionMessage: "We'd like to show you notifications for the latest news and updates.",
        /* acceptButtonText limited to 15 characters */
        acceptButtonText: "ALLOW",
        /* cancelButtonText limited to 15 characters */
        cancelButtonText: "NO THANKS"
      }
    }]);
  </script>
</head>

HTTP Pop-Up Prompt

The HTTP Pop-Up Prompt is required for HTTP sites.

HTTP - The HTTP Pop-Up Prompt comes up after a user clicks on another prompt like our Subscription Bell, Slide Prompt, or Custom Link.

This section shows you how to trigger and customize the HTTP Pop-Up Prompt. If you want to learn more about asking for push notification permissions, go here.

The HTTP Pop-Up Prompt is presented in a separate pop-up window:

Trigger HTTP Pop-Up

Custom Code - You may create your own button or link that calls registerForPushNotifications() to trigger the HTTP Pop-Up Prompt.

Customize HTTP Pop-Up Prompt

Custom Code for HTTP only

To customize the text, buttons, and images in the HTTP Pop-Up Prompt, use the promptOptions parameter in your init() options. You may change all text except the URL on the notification image (yourlabel.os.tc). You may enter text in your own language, but please note all fields are limited in length (usually to one line of text). Any fields you do not define will use their defaults.

// Do NOT call init() twice
OneSignal.push(["init", {
    // Your other init options here
    promptOptions: {
        /* Change bold title, limited to 30 characters */
        siteName: 'OneSignal Documentation',
        /* Subtitle, limited to 90 characters */
        actionMessage: "We'd like to show you notifications for the latest news and updates.",
        /* Example notification title */
        exampleNotificationTitle: 'Example notification',
        /* Example notification message */
        exampleNotificationMessage: 'This is an example notification',
        /* Text below example notification, limited to 50 characters */
        exampleNotificationCaption: 'You can unsubscribe anytime',
        /* Accept button text, limited to 15 characters */
        acceptButtonText: "ALLOW",
        /* Cancel button text, limited to 15 characters */
        cancelButtonText: "NO THANKS"
    }
}]);

Customizing "Click Allow": Set the autoAcceptTitle of promptOptions:

// Do NOT call init() twice
OneSignal.push(["init", {
    // Your other init options here
    promptOptions: {
        /* Change click allow text, limited to 30 characters */
        autoAcceptTitle: 'Click Allow',
        /* ... */
    }
}]);

Customizing Icon

You may customize the website icon shown in the HTTP Pop-Up Prompt by editing the Default Notification Icon URL in your dashboard.

To edit the website icon, enter a link to an icon file that is at least 80x80 pixels (Recommended size is 192x192). The file must be .png or .jpg.

If you do not have a Default Notification Icon URL set, OneSignal will show a generic icon.

Full Code Example HTTP Pop-Up Prompt

<head>
  <script src="https://cdn.onesignal.com/sdks/OneSignalSDK.js" async='async'></script>
  <script>
    var OneSignal = window.OneSignal || [];
    OneSignal.push(["init", {
      appId: "YOUR_APP_ID",
      autoRegister: false, /* Set to true to automatically prompt visitors */
      httpPermissionRequest: {
        enable: true
      },
      notifyButton: {
          enable: true /* Set to false to hide */
      },
      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) */
      },
      promptOptions: {
        /* Change bold title, limited to 30 characters */
        siteName: 'OneSignal Documentation',
        /* Subtitle, limited to 90 characters */
        actionMessage: "We'd like to show you notifications for the latest news and updates.",
        /* Example notification title */
        exampleNotificationTitle: 'Example notification',
        /* Example notification message */
        exampleNotificationMessage: 'This is an example notification',
        /* Text below example notification, limited to 50 characters */
        exampleNotificationCaption: 'You can unsubscribe anytime',
        /* Accept button text, limited to 15 characters */
        acceptButtonText: "ALLOW",
        /* Cancel button text, limited to 15 characters */
        cancelButtonText: "NO THANKS"
      }
    }]);
    OneSignal.push(function() {
      OneSignal.registerForPushNotifications();
    });
  </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 when clicked.

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 (state.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>

Permission Requests

Custom Code - HTTPS Only

Permission Requests appear directly from the browser asking users to allow notification permissions. Users are directly subscribed after clicking Allow, without any further interaction required.

Unlike prompts, if you present users with the browser's permission request and users click Block, your site will never be able to prompt users again to register for push notifications. This is why we recommend customers use one of the above prompts instead.

The only way to get around a user blocking your site's push notifications forever is to show them how to manually change their browser settings - which users rarely do.

Automatically triggering Permission Requests

Custom Code - Not Recommended - We do not recommend clients automatically trigger permission requests because it creates a poor user experience.

The browser permission request is automatically shown when:

  1. Your OneSignal JavaScript initialization settings contains the autoRegister: true property.

    Note: OneSignal will ignore this for users with Chrome on Android, due to changes in that browser's prompting behavior. Read more

  2. The user has not clicked the X button to dismiss the request. Users who dismiss the prompt will not see it again for 8 hours.

    Note: Chrome on Android does not show the 'X' button, meaning users cannot dismiss these prompts. Read more

Wordpress - In the Configuration tab of our WordPress plugin, you must additionally enable Automatically prompt new site visitors to subscribe to push notification.

Manually triggering Permission Requests

The browser permission request can be triggered manually via registerForPushNotifications(). You may wish to do this after presenting users a prompt, such as the Slide Prompt. Note that Permissions Requests may not always appear.

OneSignal does not recommend triggering Permission Requests without users first opting-in via another prompting method. We only recommend manually triggering Permission Requests when you have presented users with an appropriate prompt first.

Customizing Permission Requests

Permission Requests are not customizable because they are shown by the device or browser. All devices and browsers present the request in the appropriate language.


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='async'></script>
  <script>
    var OneSignal = window.OneSignal || [];
    OneSignal.push(["init", {
      appId: "YOUR_APP_ID",
      autoRegister: false, /* Set to true to automatically prompt visitors */
      httpPermissionRequest: {
        enable: true
      },
      notifyButton: {
          enable: true /* Set to false to hide */
      },
      subdomainName: "your_label" /* The label for your site that you added in Site Setup mylabel.os.tc */
    }]);
  </script>
</head>

Prompt Behavior

Add Delay to Prompt

Wordpress Users please see how do I delay prompting on Wordpress docs

HTTPS SETUP for Delay

ONLY USE THIS CODE ONCE PER PAGE

<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(["init", {
            appId: "YOUR_APP_ID",
            autoRegister: false,
            notifyButton: {
                enable: true /* Set to false to hide */
            },
            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) */
            },
            promptOptions: {
                /* actionMessage limited to 90 characters */
                actionMessage: "We'd like to show you notifications for the latest news and updates.",
                /* acceptButtonText limited to 15 characters */
                acceptButtonText: "ALLOW",
                /* cancelButtonText limited to 15 characters */
                cancelButtonText: "NO THANKS"
            }
        }]);
    </script>
    <script data-cfasync="false">
        window.OneSignal = window.OneSignal || [];

        /* In milliseconds, time to wait before prompting user. This time is relative to right after the user presses <ENTER> on the address bar and navigates to your page */
        var notificationPromptDelay = 30000;

        /* Why use .push? See: http://stackoverflow.com/a/38466780/555547 */
        window.OneSignal.push(function() {
            /* Use navigation timing to find out when the page actually loaded instead of using setTimeout() only which can be delayed by script execution */
            var navigationStart = window.performance.timing.navigationStart;

            /* Get current time */
            var timeNow = Date.now();

            /* Prompt the user if enough time has elapsed */
            setTimeout(promptAndSubscribeUser, Math.max(notificationPromptDelay - (timeNow - navigationStart), 0));
        });

        function promptAndSubscribeUser() {
            window.OneSignal.isPushNotificationsEnabled(function(isEnabled) {
                if (!isEnabled) {
                  /* Want to trigger different permission messages? See: https://documentation.onesignal.com/docs/permission-requests#section-onesignal-permission-messages */
                    window.OneSignal.showHttpPrompt();
                }
            });
        }
    </script>
</head>

HTTP SETUP for Delay

ONLY USE THIS CODE ONCE PER PAGE

<head>
    <script src="https://cdn.onesignal.com/sdks/OneSignalSDK.js" async='async'></script>
    <script>
        var OneSignal = window.OneSignal || [];
        OneSignal.push(["init", {
            appId: "YOUR_APP_ID",
            autoRegister: false,
            notifyButton: {
                enable: true /* Set to false to hide */
            },
            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) */
            },
            promptOptions: {
                /* actionMessage limited to 90 characters */
                actionMessage: "We'd like to show you notifications for the latest news and updates.",
                /* acceptButtonText limited to 15 characters */
                acceptButtonText: "ALLOW",
                /* cancelButtonText limited to 15 characters */
                cancelButtonText: "NO THANKS"
            }
        }]);
    </script>
    <script data-cfasync="false">
        window.OneSignal = window.OneSignal || [];

        /* In milliseconds, time to wait before prompting user. This time is relative to right after the user presses <ENTER> on the address bar and navigates to your page */
        var notificationPromptDelay = 30000;

        /* Why use .push? See: http://stackoverflow.com/a/38466780/555547 */
        window.OneSignal.push(function() {
            /* Use navigation timing to find out when the page actually loaded instead of using setTimeout() only which can be delayed by script execution */
            var navigationStart = window.performance.timing.navigationStart;

            /* Get current time */
            var timeNow = Date.now();

            /* Prompt the user if enough time has elapsed */
            setTimeout(promptAndSubscribeUser, Math.max(notificationPromptDelay - (timeNow - navigationStart), 0));
        });

        function promptAndSubscribeUser() {
            window.OneSignal.isPushNotificationsEnabled(function(isEnabled) {
                if (!isEnabled) {
                  /* Want to trigger different permission messages? See: https://documentation.onesignal.com/docs/permission-requests#section-onesignal-permission-messages */
                    window.OneSignal.showHttpPrompt();
                }
            });
        }
    </script>
</head>

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
}]);