{"__v":163,"_id":"551ef4f04986f62b00a7206f","category":{"__v":11,"_id":"551ef4ef4986f62b00a7203e","pages":["551ef4f04986f62b00a7206d","551ef4f04986f62b00a7206e","551ef4f04986f62b00a7206f","552359b8e20da719000e797b","5536d74bc36ca60d003c5540","5548372bd2c8410d006c212d","55d77b86f662951900fc0ef5","5605b89024c9d80d001551fd","5668806406039e0d00c4ed24","56688887ee1dbf0d008f62a7","568c6de813c5ad0d00b34e4d","5699b35bcb127f0d003cc1ba","56cbe4638df25d0b00e8d774"],"project":"542b6018044e1e2200413772","version":"551ef4ef4986f62b00a7202e","reference":false,"createdAt":"2015-03-24T04:27:30.031Z","from_sync":false,"order":7,"slug":"website-push","title":"Website Push"},"parentDoc":null,"project":"542b6018044e1e2200413772","user":"54455ea0a21e4d140055dc08","version":{"__v":7,"_id":"551ef4ef4986f62b00a7202e","forked_from":"542b6018044e1e2200413775","project":"542b6018044e1e2200413772","createdAt":"2015-04-03T20:15:43.149Z","releaseDate":"2015-04-03T20:15:43.149Z","categories":["551ef4ef4986f62b00a7202f","551ef4ef4986f62b00a72030","551ef4ef4986f62b00a72031","551ef4ef4986f62b00a72032","551ef4ef4986f62b00a72033","551ef4ef4986f62b00a72034","551ef4ef4986f62b00a72035","551ef4ef4986f62b00a72036","551ef4ef4986f62b00a72037","551ef4ef4986f62b00a72038","551ef4ef4986f62b00a72039","551ef4ef4986f62b00a7203a","551ef4ef4986f62b00a7203b","551ef4ef4986f62b00a7203c","551ef4ef4986f62b00a7203d","551ef4ef4986f62b00a7203e","55d7f1879510f00d007ec727","56b94a5a9fc0de1700b60ae9","56bd0e48ac1c5c1900b2dbe4","56d74afc3eb4dd0b0020196a","5723ab8a1f41110e003081ed","576b4dd327d6252b00085422"],"is_deprecated":false,"is_hidden":false,"is_beta":false,"is_stable":true,"codename":"","version_clean":"2.0.0","version":"2.0"},"updates":[],"createdAt":"2015-03-24T22:17:29.504Z","link_external":false,"link_url":"","githubsync":"","sync_unique":"","hidden":false,"api":{"results":{"codes":[]},"settings":"","auth":"required","params":[],"url":""},"isReference":false,"order":9,"body":"[block:callout]\n{\n  \"type\": \"info\",\n  \"title\": \"Loading SDK Asynchronously\",\n  \"body\": \"OneSignal supports loading `OneSignalSDK.js` with the `async` flag so your page load times don't increase. To use it, place the following code *before* calling any other OneSignal functions.\\n\\n```html\\n<script src=\\\"https://cdn.onesignal.com/sdks/OneSignalSDK.js\\\" async></script>\\n<script>var OneSignal = OneSignal || [];</script>\\n```\\n\\nOur API functions can be called asynchronously using either:\\n\\n1. `OneSignal.push([\\\"functionName\\\", param1, param2]);`\\n2. `OneSignal.push(function() { OneSignal.functionName(param1, param2); });`\\n\\nOption 2 must be used for functions that return a value like isPushNotificationsSupported. Option 2 also lets you call as many OneSignal functions as you need inside the passed in function.\"\n}\n[/block]\n\n[block:html]\n{\n  \"html\": \"<div></div>\\n\\n<style></style>\"\n}\n[/block]\n\n[block:api-header]\n{\n  \"type\": \"basic\",\n  \"title\": \"List of Functions\"\n}\n[/block]\n[init](#init)\n\n[registerForPushNotifications](#registerForPushNotifications)\n\n[setDefaultNotificationUrl](#setDefaultNotificationUrl)\n\n[setDefaultTitle](#setDefaultTitle)\n\n[sendTag](#sendTag)\n\n[sendTags](#sendTags)\n\n[getTags](#getTags)\n\n[deleteTag](#deleteTag)\n\n[deleteTags](#deleteTags)\n\n[isPushNotificationsSupported](#isPushNotificationsSupported)\n\n[isPushNotificationsEnabled](#isPushNotificationsEnabled)\n\n[getUserId](#getUserId)\n\n[getRegistrationId](#getRegistrationId)\n\n[getNotificationPermission](#getNotificationPermission)\n\n[addListenerForNotificationOpened](#addListenerForNotificationOpened)\n\n[setSubscription](#section-setsubscription-optout-)\n\n[sendSelfNotification](#sendSelfNotification)\n\n[showHttpPrompt](#showHttpPrompt)\n[block:html]\n{\n  \"html\": \"<br>\"\n}\n[/block]\n\n[block:api-header]\n{\n  \"type\": \"basic\",\n  \"title\": \"List of Events\"\n}\n[/block]\nEach of the provided events can be listened to via the `on()` or `once()` listener:\n[block:code]\n{\n  \"codes\": [\n    {\n      \"code\": \"// Make sure OneSignal is initialized before listening to the event\\nvar OneSignal = OneSignal || [];\\nOneSignal.on('(event name here)', function(event) {\\n  // This callback fires every time the event occurs\\n});\\nOneSignal.once('(event name here)', function(event) {\\n  // This callback fires only once when the event occurs, and does not refire\\n});\",\n      \"language\": \"javascript\"\n    }\n  ]\n}\n[/block]\n[Subscription Change](#subscriptionChangeEvent)\n[Notification Display](#notificationDisplayEvent)\n[Notification Dismiss](#notificationDismissEvent)\n[block:api-header]\n{\n  \"type\": \"basic\",\n  \"title\": \"List of Callbacks\"\n}\n[/block]\n[tagsReceivedCallBack](#tagsReceivedCallBack)\n\n[notificationOpenedCallBack](#notificationOpenedCallBack)\n[block:html]\n{\n  \"html\": \"<br><br>\"\n}\n[/block]\n\n[block:api-header]\n{\n  \"type\": \"basic\",\n  \"title\": \"Functions\"\n}\n[/block]\n\n[block:html]\n{\n  \"html\": \"<a name=\\\"init\\\">\"\n}\n[/block]\n## init()\nCall this from each page of your site to initialize OneSignal.\n\nNotes:\n- Do not call this method twice. Doing so results in an error.\n- This call is required before any other function can be used.\n\n__Parameters__\n - __`JSON` _options___\n    - __`String` _appId___ - Your OneSignal app id found on the settings page at onesignal.com.\n    - __`String` _subdomainName (Required HTTP, Optional HTTPS)___ - This must match the Subdomain you entered on the Web Push settings on the OneSignal dashboard.\n    - __`Boolean` _autoRegister (Optional, Available for HTTPS only)___ -Default true. Automatically show browser prompt to accept notifications. You can pass in false to delay this pop-up and then call `registerForPushNotifications` to prompt them later. Only works for HTTPS.\n    - __`String` _path (Available For HTTPS only)___ - Normally you will want to set as \"/\" to indicate your OneSignalSDKWorker.js and OneSignalSDKUpdaterWorker.js are at the root of your domain. Example https://yourdomain.com/OneSignalSDKUpdaterWorker.js and https://yourdomain.com/OneSignalSDKUpdaterWorker.js should both be accessible.\n    - __`JSON` _promptOptions (Optional)___ - Use these parameters to localize the HTTP popup prompt to your custom text and language. All entries are limited in length. Foreign characters accepted. Each parameter is optional, and its default is used when it is not included.\n        -  __`String` _actionMessage (Optional)___ - Text that says 'wants to show notifications' by default. Limited to 75 characters.\n        -  __`String` _exampleNotificationTitleDesktop (Optional)___ - Text that says 'This is an example notification'. Displays on non-mobile devices. Only one line is allowed.\n        -  __`String` _exampleNotificationMessageDesktop (Optional)___ - Text that says 'Notifications will appear on your desktop'. Displays on non-mobile devices. Only one line is allowed.\n        -  __`String` _exampleNotificationTitleMobile (Optional)___ - Text that says 'This is an example notification'. Displays on mobile devices with limited screen width. Only one line is allowed.\n        -  __`String` _exampleNotificationMessageMobile (Optional)___ - Text that says 'Notifications will appear on your device'. Displays on mobile devices with limited screen width. Only one line is allowed.\n        -  __`String` _exampleNotificationCaption (Optional)___ - Text that says '(you can unsubscribe anytime)'.\n        -  __`String` _acceptButtonText (Optional)___ - Text that says 'CONTINUE'.\n        -  __`String` _cancelButtonText (Optional)___ - Text that says 'NO THANKS'.\n        -  __`Boolean` _showCredit (Optional)___ - Set to false to hide the OneSignal logo.\n    - __`JSON` _welcomeNotification (Optional)___ - Use these parameters to customize or disable the welcome notification sent to new site visitors. Any person visiting your site for their first time, or an existing user who has completely cleared their cache is considered a new site visitor.\n        -  __`Boolean` _disable (Optional)___ - Disables sending a welcome notification to new site visitors. If you want to disable welcome notifications, this is the only option you need.\n        -  __`String` _title (Optional)___ - The welcome notification's title. You can localize this to your own language. If not set, or left blank, the site's title will be used. Set to one space ' ' to clear the title, although this is not recommended.\n        -  __`String` _message (Required)___ - The welcome notification's message. You can localize this to your own language. A message is required. If left blank or set to blank, the default of 'Thanks for subscribing!' will be used.\n    - __`JSON` _notifyButton (Optional)___ - Use these parameters to enable and customize the notifyButton. All parameters below are optional. If not set, they will be replaced with their defaults.\n        -  __`Boolean` _enable___ - Enable the notify button. The notify button is otherwise disabled by default.\n        -  __`String` _size___ - One of 'small', 'medium', or 'large'. The notify button will initially appear at one of these sizes, and then shrink down to size 'small' after the user subscribes.\n        -  __`String` _position___ - Either 'bottom-left' or 'bottom-right'. The notify button will be fixed at this location on your page.\n        - __`JSON` _offset___ - Specify CSS-valid pixel offsets using bottom, left, and right.\n        -  __`Boolean` _modalPrompt___ - If you use the modal prompt for your HTTPS website, you should specify it here too so the bell shows the modal instead of the popup.\n        -  __`Boolean` _prenotify___ - If true, the notify button will display an icon that there is 1 unread message. When hovering over the notify button, the user will see custom text set by `message.prenotify`.\n        -  __`Boolean` _showCredit___ - Set false to hide the 'Powered by OneSignal' text in the notify button dialog popup.\n        -  __`JSON` _text___ - Customize the notify button text. See the example code below to know what to change.\n    - __`Boolean` _persistNotification (Optional)___ - Applies only on Chrome Desktop 47+. If false, the notification will disappear roughly after 20 seconds. If true, the notification will be displayed indefinitely until the user interacts with the notification (dismisses it or clicks it). If this optional value is not set, it defaults to true (i.e. notifications by default persist indefinitely). On Firefox and Safari, notifications automatically dismiss after some time and this parameter does not control that.\n    - __`JSON` _webhooks (Optional)___ - See our [Webhooks page](doc:webhooks) for the nested options.\n \n**Simple Example**\n\nThe following is a basic template of how you would call init(). [See our Customizing Features page to see additional examples.](doc:customizing-features) \n[block:code]\n{\n  \"codes\": [\n    {\n      \"code\": \"// OneSignal is defined as an array here and uses push calls to support OneSignalSDK.js being loaded async.\\nvar OneSignal = OneSignal || [];\\n\\nOneSignal.push([\\\"init\\\", {\\n  appId: \\\"YOUR_APP_ID\\\",\\n  // Your other init settings\\n}]);\",\n      \"language\": \"javascript\"\n    }\n  ]\n}\n[/block]\n\n[block:html]\n{\n  \"html\": \"<br><a name=\\\"registerForPushNotifications\\\">\"\n}\n[/block]\n## registerForPushNotifications()\nPrompts the user to subscribe to your site's notifications, or if the user has already subscribed, does nothing. For HTTPS sites, the native browser subscription prompt is displayed. For HTTP sites, a popup prompt is displayed instead.\n\nSee the `subscriptionChange` event to know when the user has successfully subscribed.\n\n__Parameters__\n- __`JSON` _options(Optional)___\n    - __`Boolean` _modalPrompt (Optional)___ - Shows a modal popup window on your page explaining and showing an example notification with an option to continue or cancel before showing the native notification prompt to accept notifications. * (Option is only available for HTTPS when not using a subdomain. Otherwise a popup window will show with the same results.)*\n \n__Example__\n[block:code]\n{\n  \"codes\": [\n    {\n      \"code\": \"OneSignal.push([\\\"registerForPushNotifications\\\"]);\\n// Optional: OneSignal.push([\\\"registerForPushNotifications\\\", {modalPrompt: true}]);\",\n      \"language\": \"javascript\"\n    }\n  ]\n}\n[/block]\n\n[block:html]\n{\n  \"html\": \"<br><a name=\\\"setDefaultNotificationUrl\\\">\"\n}\n[/block]\n## setDefaultNotificationUrl(url)\nPass in the full URL of the default page you want to open when a notification is clicked.\n\n- __Parameters__\n  - __`String` _url___ - page url to open from notifications\n\n__Example__\n[block:code]\n{\n  \"codes\": [\n    {\n      \"code\": \"OneSignal.push([\\\"setDefaultNotificationUrl\\\", \\\"https://domain.com/index2\\\"]);\",\n      \"language\": \"javascript\"\n    }\n  ]\n}\n[/block]\n\n[block:html]\n{\n  \"html\": \"<br><a name=\\\"setDefaultIcon\\\">\"\n}\n[/block]\n\n[block:html]\n{\n  \"html\": \"<br><a name=\\\"setDefaultTitle\\\">\"\n}\n[/block]\n## setDefaultTitle(title)\nSets the default title to display on notifications. Will default to the page's `document.title` if you don't call this.\n\n- __Parameters__\n  - __`String` _title___ - String to set as a default title on notifications\n\n__Example__\n[block:code]\n{\n  \"codes\": [\n    {\n      \"code\": \"OneSignal.push([\\\"setDefaultTitle\\\", \\\"Custom Default Title\\\"]);\",\n      \"language\": \"javascript\"\n    }\n  ]\n}\n[/block]\n\n[block:html]\n{\n  \"html\": \"<br><a name=\\\"sendTag\\\">\"\n}\n[/block]\n## sendTag (key, value, callback)\nTag a user based on an app event of your choosing so later you can create segments on [onesignal.com](https://onesignal.com) to target these users. Recommend using sendTags over sendTag if you need to set more than one tag on a user at a time. \n\nYou can call `OneSignal.push([\"sendTag\", \"key\", \"value\"])` anytime after `var OneSignal = OneSignal || [];`; you do not have to wait until the user registers. Once the user registers, the tags will automatically be sent to our server as long as the page session is the same (i.e. the user has not navigated to another page).\n\n- __Parameters__\n - __`string` _key___ - Key of your choosing to create or update.\n - __`string` _value___ - Value to set on the key.\n     - _NOTE:_ Passing in a blank String deletes the key, you can also call deleteTag.\n - __`Function` _callback___ - Call back to be fired when the tags have been sent to our server and a response has been returned. The first parameter of the callback is an object of the tags you sent (key-value pairs).\n\nReturns a `Promise` that is resolved with the object key-pairs of the tags you sent, or rejected with an error.\n \n__Example__\n[block:code]\n{\n  \"codes\": [\n    {\n      \"code\": \"OneSignal.push([\\\"sendTag\\\", \\\"key\\\", \\\"value\\\", function(tagsSent) {\\n  // Callback called when tags have finished sending\\n}]);\",\n      \"language\": \"javascript\"\n    }\n  ]\n}\n[/block]\n\n[block:html]\n{\n  \"html\": \"<br><a name=\\\"sendTags\\\">\"\n}\n[/block]\n## sendTags(keyValues, callback)\nTag a user based on an app event of your choosing so later you can create segments on [onesignal.com](https://onesignal.com) to target these users.\n\nYou can call `OneSignal.push([\"sendTags\", {key2: \"value2\", key3: \"value3\"}])` anytime after `var OneSignal = OneSignal || [];`; you do not have to wait until the user registers. Once the user registers, the tags will automatically be sent to our server.\n\n- __Parameters__\n - __`JSON` _keyValues___ - Key value pairs of your choosing to create or update.\n   - _NOTE:_ Passing in a blank String as a value deletes the key, you can also call deleteTag or deleteTags.\n - __`Function` _callback___ - Call back to be fired when the tags have been sent to our server and a response has been returned. The first parameter of the callback is an object of the tags you sent (key-value pairs).\n\nReturns a `Promise` that is resolved with the object key-pairs of the tags you sent, or rejected with an error.\n\n \n__Example__\n[block:code]\n{\n  \"codes\": [\n    {\n      \"code\": \"OneSignal.push([\\\"sendTags\\\", {key2: \\\"value2\\\", key3: \\\"value3\\\"}, function() {\\n  // Callback called when tags have finished sending  \\n}]);\",\n      \"language\": \"javascript\"\n    }\n  ]\n}\n[/block]\n\n[block:html]\n{\n  \"html\": \"<br><a name=\\\"getTags\\\">\"\n}\n[/block]\n## getTags(callback)\nRetrieve a list of tags that have been set on the user from the OneSignal server.\n\n- __Parameters__\n - __`Function` _callback___ - Callback to be fired when the list of tags has been retrieved. The first parameter of the callback is an object containing key-value pairs of the tags.\n\nReturns a `Promise` that is resolved with the object key-pairs of the tags you sent, or rejected with an error.\n\n__Example__\n[block:code]\n{\n  \"codes\": [\n    {\n      \"code\": \"OneSignal.push([\\\"getTags\\\", function(tags) {\\n\\t\\tconsole.log(\\\"OneSignal getTags:\\\", tags);\\n\\t}]);\",\n      \"language\": \"javascript\"\n    }\n  ]\n}\n[/block]\n\n[block:html]\n{\n  \"html\": \"<br><a name=\\\"deleteTag\\\">\"\n}\n[/block]\n## deleteTag(key)\nDeletes a tag that was previously set on a user with `sendTag` or `sendTags`. Use `deleteTags` if you need to delete more than one.\n\n- __Parameters__\n - __`String` _key___ - Key to remove.\n   \nReturns a `Promise` that is resolved with the object key-pair of the tag you deleted, or rejected with an error.   \n \n__Example__\n[block:code]\n{\n  \"codes\": [\n    {\n      \"code\": \"OneSignal.push([\\\"deleteTag\\\", \\\"key\\\"]);\",\n      \"language\": \"javascript\"\n    }\n  ]\n}\n[/block]\n\n[block:html]\n{\n  \"html\": \"<br><a name=\\\"deleteTags\\\">\"\n}\n[/block]\n## deleteTags(keys, callback)\nDeletes tags that were previously set on a user with `sendTag` or `sendTags`.\n\n- __Parameters__\n - __`Array` _keys___ - Keys to remove.\n - __`Function` _callback___ - Callback to be fired when the list of tags has been removed. The first parameter of the callback is an array of the tags that were deleted.\n\nReturns a `Promise` that is resolved with the object key-pairs of the tags you deleted, or rejected with an error.   \n \n__Example__\n[block:code]\n{\n  \"codes\": [\n    {\n      \"code\": \"OneSignal.push([\\\"deleteTags\\\", [\\\"key1\\\", \\\"key2\\\"]]);\",\n      \"language\": \"javascript\"\n    }\n  ]\n}\n[/block]\n\n[block:html]\n{\n  \"html\": \"<br><a name=\\\"isPushNotificationsEnabled\\\">\"\n}\n[/block]\n## isPushNotificationsEnabled()\nPasses true to the passed in callback if the user has already accepted push notifications and successfully registered with Google's GCM server and OneSignal's server. Callback should fire within 1 second so you can change your page to reflect if notifications are enabled or not.\n\nUse [getIdsAvailable](#getIdsAvailable) you if want to only to run code after/if the user accepts push notifications and registers successfully.\n\n- __Parameters__\n - __`function`  _isPushNotificationsEnabledCallBack___ -  Passed in function which will receive one boolean parameter if they are enabled or not.\n[block:code]\n{\n  \"codes\": [\n    {\n      \"code\": \"OneSignal.push([\\\"isPushNotificationsEnabled\\\", function(enabled) {\\n\\tif (enabled)\\n    console.log(\\\"Push notifications are enabled!\\\");\\n  else\\n    console.log(\\\"Push notifications are not enabled yet.\\\");\\n}]);\",\n      \"language\": \"javascript\"\n    }\n  ]\n}\n[/block]\n\n[block:html]\n{\n  \"html\": \"<br><a name=\\\"isPushNotificationsSupported\\\">\"\n}\n[/block]\n## isPushNotificationsSupported()\nReturns true if the current browser viewing the page supports push notifications.\n[block:code]\n{\n  \"codes\": [\n    {\n      \"code\": \"OneSignal.push(function() {\\n\\tif (OneSignal.isPushNotificationsSupported())\\n    console.log(\\\"Push notifications are supported, please allow the permission to enable them\\\");\\n});\",\n      \"language\": \"javascript\"\n    }\n  ]\n}\n[/block]\n\n[block:html]\n{\n  \"html\": \"<br><a name=\\\"getUserId\\\">\"\n}\n[/block]\n## getUserId()\nReturns a Promise that resolves to the stored OneSignal user ID if one is set, otherwise the Promise resolves to null.\n\nFor custom implementations involving our REST API, associate this OneSignal user ID with your data.\n\nOnce created, the user ID will not change. If the user unsubscribes from web push, for example by clearing their browser data, and resubscribes, a new user ID will be created and a new entry will be stored on your app's users list. The old entry will not be automatically deleted.\n\n- __Parameters__\n - __`function`  _callback___ -  A callback function which sets the first parameter to the stored OneSignal user ID if one is set, otherwise the first parameter is set to null.\n\n__Example__\n[block:code]\n{\n  \"codes\": [\n    {\n      \"code\": \"OneSignal.push([\\\"getUserId\\\", function(userId) {\\n    console.log(\\\"OneSignal User ID:\\\", userId);\\n    // (Output) OneSignal User ID: 270a35cd-4dda-4b3f-b04e-41d7463a2316\\n}]);\",\n      \"language\": \"javascript\"\n    }\n  ]\n}\n[/block]\n\n[block:html]\n{\n  \"html\": \"<br><a name=\\\"getRegistrationId\\\">\"\n}\n[/block]\n## getRegistrationId()\nReturns a Promise that resolves to the stored OneSignal registration ID if one is set, otherwise the Promise resolves to null.\n\nFor custom implementations involving our REST API, use the above OneSignal user ID with your data instead of this registration ID. The registration ID is the device token associated with GCM or Apple's push notification server. It is an internal ID we use to generate the corresponding OneSignal user ID. We do not recommend using or storing the registration ID unless necessary.\n\n- __Parameters__\n - __`function`  _callback___ -  A callback function which sets the first parameter to the stored OneSignal registration ID if one is set, otherwise the first parameter is set to null.\n\n__Example__\n[block:code]\n{\n  \"codes\": [\n    {\n      \"code\": \"OneSignal.push([\\\"getRegistrationId\\\", function(registrationId) {\\n    console.log(\\\"OneSignal Registration ID:\\\", registrationId);\\n    // (Output) OneSignal Registration ID: cPMqRjFKn6U:APA91bGgr5-3ny36bQxBCA7uAoQIDsUtX6q7CL4FcsDiHlGgDh471C8cEktPYzTsO2OaOCeZmB0gLSSErzwM3fcZWI9LFkW8LEQzBVw7UbQ8NtlBF0dTADoYLF87xXSztUjAkFLP5_Vy\\n}]);\",\n      \"language\": \"javascript\"\n    }\n  ]\n}\n[/block]\n\n[block:html]\n{\n  \"html\": \"<br><a name=\\\"getNotificationPermission\\\">\"\n}\n[/block]\n## getNotificationPermission()\nReturns a Promise that resolves to the browser's current notification permission as 'default', 'granted', or 'denied'.\n\nYou can use this to detect whether the user has allowed notifications, blocked notifications, or has not chosen either setting.\n\n- __Parameters__\n - __`function`  _callback___ -  A callback function that will be called when the browser's current notification permission has been obtained, with one of 'default', 'granted', or 'denied'.\n\n__Example__\n[block:code]\n{\n  \"codes\": [\n    {\n      \"code\": \"OneSignal.push([\\\"getNotificationPermission\\\", function(permission) {\\n    console.log(\\\"Site Notification Permission:\\\", permission);\\n    // (Output) Site Notification Permission: default\\n}]);\",\n      \"language\": \"javascript\"\n    }\n  ]\n}\n[/block]\n\n[block:html]\n{\n  \"html\": \"<br><a name=\\\"addListenerForNotificationOpened\\\">\"\n}\n[/block]\n## addListenerForNotificationOpened(callback)\nPassed in callback that fires when the user clicks on a OneSignal notification. Please see the [callback documentation](https://documentation.onesignal.com/docs/website-sdk-api#section-notificationopenedcallback) as specific cases are required to trigger this event.\n\n- __Parameters__\n - __`function`  _notificationOpenedCallBack___ -  Passed in function which will receive one parameter containing JSON with data about the notification that was clicked.\n\n__Example__\n[block:code]\n{\n  \"codes\": [\n    {\n      \"code\": \"OneSignal.push([\\\"addListenerForNotificationOpened\\\", function(data) {\\n\\tconsole.log(\\\"Received NotificationOpened:\\\");\\n\\tconsole.log(data);\\n}]);\",\n      \"language\": \"javascript\"\n    }\n  ]\n}\n[/block]\n<br><div id=\"setSubscription \">\n## setSubscription(optOut)\nOneSignal.setSubscription() is used to temporarily opt-out the user from receiving notifications by setting a flag on our system so that notifications are not delivered to the user. Set to false to temporarily \"mute\" notifications from going to the user. If you previously set this to false, you can set it to true to \"un-mute\" notifications so that the user receives them again. **This event is not related to actually prompting the user to subscribe. The user must already be subscribed.**\n\n- __Parameters__\n - __`boolean`  _enable___\n\n__Example__\n[block:code]\n{\n  \"codes\": [\n    {\n      \"code\": \"OneSignal.push([\\\"setSubscription\\\", false]);\",\n      \"language\": \"javascript\"\n    }\n  ]\n}\n[/block]\n\n[block:html]\n{\n  \"html\": \"<br/><a name=\\\"sendSelfNotification\\\">\"\n}\n[/block]\n## sendSelfNotification(title, message, url, icon, data)\nSends a push notification to the current user on the webpage. This is a simplified utility function to send a test message to yourself or a quick message to the user. It does not support any targeting options.\n\n- __Parameters__\n - __`String`  _title___ -  The notification's title. Currently defaults to \"OneSignal Test Message\" if not set. Use a \" \" single space to get around this. Multiple languages are not supported; write the text in the language the current user should receive it in.\n - __`String` _message___ - The notification's body content. Required. Multiple languages are not supported; write the text in the language the current user should receive it in.\n - __`String` _url___ - The URL to launch when the notification is clicked.[ Use a special URL to prevent any URL from launching](https://documentation.onesignal.com/docs/web-push-action-buttons#how-can-i-prevent-the-action-button-from-opening-a). Defaults to this special URL if none is set.\n - __`String` _icon___ - The URL to use for the notification icon.\n - __`Hash` _data___ - Additional data to pass for the notification.\n - __`Array of Hash` _buttons___ - See [Action Buttons](doc:web-push-action-buttons) docs.\n - \n__Example__\n[block:code]\n{\n  \"codes\": [\n    {\n      \"code\": \"OneSignal.sendSelfNotification(\\n  /* Title (defaults if unset) */\\n  \\\"OneSignal Web Push Notification\\\",\\n  /* Message (defaults if unset) */\\n  \\\"Action buttons increase the ways your users can interact with your notification.\\\", \\n   /* URL (defaults if unset) */\\n  'https://example.com/?_osp=do_not_open',\\n  /* Icon */\\n  'https://onesignal.com/images/notification_logo.png',\\n  {\\n    /* Additional data hash */\\n    notificationType: 'news-feature'\\n  }, \\n  [{ /* Buttons */\\n    /* Choose any unique identifier for your button. The ID of the clicked button        is passed to you so you can identify which button is clicked */.\\n    id: 'like-button',\\n    /* The text the button should display. Supports emojis. */\\n    text: 'Like',\\n    /* A valid publicly reachable URL to an icon. Keep this small because it's         downloaded on each notification display. */\\n    icon: 'http://i.imgur.com/N8SN8ZS.png',\\n    /* The URL to open when this action button is clicked. See the sections below        for special URLs that prevent opening any window. */\\n    url: 'https://example.com/?_osp=do_not_open'\\n  },\\n  {\\n    id: 'read-more-button',\\n    text: 'Read more',\\n    icon: 'http://i.imgur.com/MIxJp1L.png',\\n    url: 'https://example.com/?_osp=do_not_open'\\n  }]\\n);\",\n      \"language\": \"javascript\"\n    }\n  ]\n}\n[/block]\n\n[block:html]\n{\n  \"html\": \"<br/><a name=\\\"showHttpPrompt\\\">\"\n}\n[/block]\n## showHttpPrompt()\nShows a prompt for HTTP site users to subscribe to notifications. Please see [HTTP Prompt](doc:web-push-http-prompt) for more details.\n\n__Example__\n[block:code]\n{\n  \"codes\": [\n    {\n      \"code\": \"OneSignal.showHttpPrompt();\",\n      \"language\": \"javascript\"\n    }\n  ]\n}\n[/block]\n\n[block:html]\n{\n  \"html\": \"<br><br><br>\"\n}\n[/block]\n\n[block:api-header]\n{\n  \"type\": \"basic\",\n  \"title\": \"Events\"\n}\n[/block]\n\n[block:html]\n{\n  \"html\": \"<a name=\\\"subscriptionChangeEvent\\\">\"\n}\n[/block]\n#### Subscription Change Event\nOccurs when the user's subscription state changes between unsubscribed and subscribed.\n\nOn Chrome and Firefox, the user's subscription is true when:\n- Your site is granted notification permissions\n- Your site visitor's web storage database containing OneSignal-related data is intact\n- You have not manually opted out the user from receiving notifications\n    - The notify button's 'Subscribe' and 'Unsubscribe' button opts users in and out without affecting their other subscription parameters\n    - `OneSignal.setSubscription()` is used to opt the user in and out\n- Your site visitor has an installed background web worker used to display notifications\n\nOn Safari, only the first three are required for a valid subscription.\n\nUse this event to find out when the user has successfully subscribed. The parameter will be set to true to represent a new subscribed state.\n\nA user is no longer subscribed if:\n- The user changes notification permissions\n    - The icon next to the URL in the address bar can be clicked to modify site permissions\n    - Chrome and Firefox notifications come with a button on the notification to block site notifications\n- The user clears their browser data (clearing cookies will not effect subscription)\n- Another background web worker overwrites our web worker\n\nThis event *is not related* to `OneSignal.setSubscription()`. `OneSignal.setSubscription()` is used to temporarily opt-out the user from receiving notifications by setting a flag on our system so that notifications are not delivered to the user. This event is more like an event for when `OneSignal.isPushNotificationsEnabled()` changes.\n\n   - __Callback Event Parameters__\n     - __`Boolean` _subscribed___ - Set to true if the user is currently subscribed; otherwise set to false.\n\n__Example__\n[block:code]\n{\n  \"codes\": [\n    {\n      \"code\": \"OneSignal.push(function() {\\n  // Occurs when the user's subscription changes to a new value.\\n  OneSignal.on('subscriptionChange', function (isSubscribed) {\\n    console.log(\\\"The user's subscription state is now:\\\", isSubscribed);\\n  });\\n});\",\n      \"language\": \"javascript\"\n    }\n  ]\n}\n[/block]\n\n[block:html]\n{\n  \"html\": \"<a name=\\\"notificationDisplayEvent\\\">\"\n}\n[/block]\n## Notification Display Event\nOccurs after a notification is visibly displayed on the user's screen.\n\nSupported On: Chrome and Firefox, not supported on Safari.\n\nThis event is fired on your page. If multiple browser tabs are open to your site, this event will be fired on *all* pages on which OneSignal is active.\n\n   - __Callback Event Parameters__\n    - __`Hash` _event___ - A JavaScript object hash containing:\n       - __`UUID` _id___ - The OneSignal notification ID of the notification that was just displayed.\n       - __`String` _heading___ - The notification's title.\n       - __`String` _content___ - The notification's body message, not including the title.\n       - __`String` _url___ - The URL that will be opened if the user clicks on the notification.\n       - __`String` _icon___ - The URL to the icon used for the notification. This is fetched every time the notification is displayed.\n\nNote: Depending on the notification, more fields (e.g. action buttons) can be included in the callback parameter.\n\n__Example__\n[block:code]\n{\n  \"codes\": [\n    {\n      \"code\": \"OneSignal.on('notificationDisplay', function (event) {\\n\\tconsole.warn('OneSignal notification displayed:', event);\\n  /*\\n  {\\n      \\\"id\\\": \\\"ce31de29-e1b0-4961-99ee-080644677cd7\\\",\\n      \\\"heading\\\": \\\"OneSignal Test Message\\\",\\n      \\\"content\\\": \\\"This is an example notification.\\\",\\n      \\\"url\\\": \\\"https://onesignal.com?_osp=do_not_open\\\",\\n      \\\"icon\\\": \\\"https://onesignal.com/images/notification_logo.png\\\"\\n  }\\n  */\\n});\",\n      \"language\": \"javascript\"\n    }\n  ]\n}\n[/block]\n\n[block:html]\n{\n  \"html\": \"<a name=\\\"notificationDismissEvent\\\">\"\n}\n[/block]\n## Notification Dismiss Event\n\nThis event occurs when:\n  - A user purposely dismisses the notification without clicking the notification body or action buttons\n  - On Chrome on Android, a user dismisses all web push notifications (this event will be fired for each web push notification we show)\n  - A notification expires on its own and disappears\n\n**Note:** This event *does not occur* if a user clicks on the notification body or one of the action buttons. That is considered a notification click (please see the `addListenerForNotificationOpened` method).\n\nSupported On: Chrome 50+ only.\n\nThis event is fired on your page. If multiple browser tabs are open to your site, this event will be fired on *all* pages on which OneSignal is active.\n\n   - __Callback Event Parameters__\n    - __`Hash` _event___ - A JavaScript object hash containing:\n       - __`UUID` _id___ - The OneSignal notification ID of the notification that was just displayed.\n       - __`String` _heading___ - The notification's title.\n       - __`String` _content___ - The notification's body message, not including the title.\n       - __`String` _url___ - The URL that will be opened if the user clicks on the notification.\n       - __`String` _icon___ - The URL to the icon used for the notification. This is fetched every time the notification is displayed.\n\nNote: Depending on the notification, more fields (e.g. action buttons) can be included in the callback parameter.\n\n__Example__\n[block:code]\n{\n  \"codes\": [\n    {\n      \"code\": \"OneSignal.on('notificationDismiss', function (event) {\\n\\tconsole.warn('OneSignal notification dismissed:', event);\\n  /*\\n  {\\n      \\\"id\\\": \\\"ce31de29-e1b0-4961-99ee-080644677cd7\\\",\\n      \\\"heading\\\": \\\"OneSignal Test Message\\\",\\n      \\\"content\\\": \\\"This is an example notification.\\\",\\n      \\\"url\\\": \\\"https://onesignal.com?_osp=do_not_open\\\",\\n      \\\"icon\\\": \\\"https://onesignal.com/images/notification_logo.png\\\"\\n  }\\n  */\\n});\",\n      \"language\": \"javascript\"\n    }\n  ]\n}\n[/block]\n\n[block:api-header]\n{\n  \"type\": \"basic\",\n  \"title\": \"Callbacks\"\n}\n[/block]\n\n[block:html]\n{\n  \"html\": \"<a name=\\\"tagsReceivedCallBack\\\">\"\n}\n[/block]\n## tagsReceivedCallBack\nGets all the tags set on a user from onesignal.com.\n\n   - __Parameters__\n     - __`JSON` _tags___ - JSON object of key value pairs retrieved from the OneSignal server.\n\n__Example__\n[block:code]\n{\n  \"codes\": [\n    {\n      \"code\": \"OneSignal.push([\\\"getTags\\\", function(tags) {\\n\\t\\tconsole.log(\\\"OneSignal getTags:\\\");\\n\\t\\tconsole.log(tags);\\n\\t}]);\",\n      \"language\": \"javascript\"\n    }\n  ]\n}\n[/block]\n\n[block:html]\n{\n  \"html\": \"<br><a name=\\\"notificationOpenedCallBack\\\">\"\n}\n[/block]\n## notificationOpenedCallBack\n\n**Note:** This functionality is only supported by Chrome and Firefox, not Safari.\n\nOccurs when a notification is clicked that opens a URL back to your page with the OneSignal SDK.\n\n**By default:**\nSuppose the notification opens the URL \"https://yoursite.com/a/b/c/\". If an existing tab is already open to the *same exact* URL, that tab will be focused and receive the callback. If no existing tab matching *the exact same URL* is open, a new browser tab will be opened and this newly opened tab will receive fire the notificationOpenedCallBack. If multiple existing tabs *all matching exactly the URL* of the notification are already open, one of the tabs will receive the callback.\n\n**Alternatively:**\n\nIn the OneSignal web SDK init options, you can set `notificationClickHandlerMatch` to the literal string `\"origin\"`. This relaxes the matching restriction above so that existing browser tabs on your site don't need to exactly match the notification URL to be focused.\n\nWith this flag set, suppose the notification opens the URL \"https://yoursite.com/a/b/c\". If you have any browser tab open to \"https://yoursite.com\", for example \"https://yoursite.com/zzz\", then the tab with \"https://yoursite.com/zzz\" or \"https://yoursite.com\" will be focused and will receive the callback. Any tab that *matches your origin* will receive the callback.\n\n*Note*: While the above is true for HTTPS sites (*any* tab that matches the origin will be focusable), for HTTP sites, the existing tab must be running the OneSignal SDK to catch the focus event from our background worker.  For HTTPS sites this restriction is not necessary.\n\nThis mode is useful for single-page apps that want to catch the event and handle their own redirection.\n\nAn *origin* is a combination of protocol, hostname, and port. https://domain.com is not the same origin as https://www.domain.com.\n\nThis callback accepts one parameter, which is a JavaScript object containing the details of the notification, as listed below:\n\n -  __JSON__\n     - __`String` _id___ - The OneSignal notification ID of the notification that was just clicked. \n     - __`String` _heading___ - Title set on the notification. \n     - __`String` _content___ - The message text the user seen in the notification.\n     - __`String` _icon___ - Icon set on the notification.\n     - __`String` _url___ - The URL that this notification opened.\n     - __`JSON` _data___ - Key value pairs that were set on the notification.\n     - __`String` _action___ - Describes whether the notification body was clicked or one of the action buttons (if present) was clicked. An empty string means the notification body was clicked, otherwise the string is set to the action button ID.\n\n__Example__\n[block:code]\n{\n  \"codes\": [\n    {\n      \"code\": \"/* Do NOT call init twice */\\nOneSignal.push([\\\"init\\\", {\\n  /* Your other init settings ... */\\n  notificationClickHandlerMatch: 'origin', /* See above documentation: 'origin' relaxes tab matching requirements *.\\n  /* ... */\\n}]);\",\n      \"language\": \"javascript\"\n    }\n  ]\n}\n[/block]\n\n[block:code]\n{\n  \"codes\": [\n    {\n      \"code\": \"OneSignal.push([\\\"addListenerForNotificationOpened\\\", function(data) {\\n\\tconsole.log(\\\"Received NotificationOpened:\\\", data);\\n}]);\",\n      \"language\": \"javascript\"\n    }\n  ]\n}\n[/block]\n\n[block:api-header]\n{\n  \"type\": \"basic\",\n  \"title\": \"Deprecations\"\n}\n[/block]\nMarch 15, 2016: Deprecated `getIdsAvailable()` in favor of `getUserId()` and `getRegistrationId()`. Deprecated `idsAvailableCallback` in favor of `subscriptionChange` event.","excerpt":"","slug":"website-sdk-api","type":"basic","title":"API Reference"}
[block:callout] { "type": "info", "title": "Loading SDK Asynchronously", "body": "OneSignal supports loading `OneSignalSDK.js` with the `async` flag so your page load times don't increase. To use it, place the following code *before* calling any other OneSignal functions.\n\n```html\n<script src=\"https://cdn.onesignal.com/sdks/OneSignalSDK.js\" async></script>\n<script>var OneSignal = OneSignal || [];</script>\n```\n\nOur API functions can be called asynchronously using either:\n\n1. `OneSignal.push([\"functionName\", param1, param2]);`\n2. `OneSignal.push(function() { OneSignal.functionName(param1, param2); });`\n\nOption 2 must be used for functions that return a value like isPushNotificationsSupported. Option 2 also lets you call as many OneSignal functions as you need inside the passed in function." } [/block] [block:html] { "html": "<div></div>\n\n<style></style>" } [/block] [block:api-header] { "type": "basic", "title": "List of Functions" } [/block] [init](#init) [registerForPushNotifications](#registerForPushNotifications) [setDefaultNotificationUrl](#setDefaultNotificationUrl) [setDefaultTitle](#setDefaultTitle) [sendTag](#sendTag) [sendTags](#sendTags) [getTags](#getTags) [deleteTag](#deleteTag) [deleteTags](#deleteTags) [isPushNotificationsSupported](#isPushNotificationsSupported) [isPushNotificationsEnabled](#isPushNotificationsEnabled) [getUserId](#getUserId) [getRegistrationId](#getRegistrationId) [getNotificationPermission](#getNotificationPermission) [addListenerForNotificationOpened](#addListenerForNotificationOpened) [setSubscription](#section-setsubscription-optout-) [sendSelfNotification](#sendSelfNotification) [showHttpPrompt](#showHttpPrompt) [block:html] { "html": "<br>" } [/block] [block:api-header] { "type": "basic", "title": "List of Events" } [/block] Each of the provided events can be listened to via the `on()` or `once()` listener: [block:code] { "codes": [ { "code": "// Make sure OneSignal is initialized before listening to the event\nvar OneSignal = OneSignal || [];\nOneSignal.on('(event name here)', function(event) {\n // This callback fires every time the event occurs\n});\nOneSignal.once('(event name here)', function(event) {\n // This callback fires only once when the event occurs, and does not refire\n});", "language": "javascript" } ] } [/block] [Subscription Change](#subscriptionChangeEvent) [Notification Display](#notificationDisplayEvent) [Notification Dismiss](#notificationDismissEvent) [block:api-header] { "type": "basic", "title": "List of Callbacks" } [/block] [tagsReceivedCallBack](#tagsReceivedCallBack) [notificationOpenedCallBack](#notificationOpenedCallBack) [block:html] { "html": "<br><br>" } [/block] [block:api-header] { "type": "basic", "title": "Functions" } [/block] [block:html] { "html": "<a name=\"init\">" } [/block] ## init() Call this from each page of your site to initialize OneSignal. Notes: - Do not call this method twice. Doing so results in an error. - This call is required before any other function can be used. __Parameters__ - __`JSON` _options___ - __`String` _appId___ - Your OneSignal app id found on the settings page at onesignal.com. - __`String` _subdomainName (Required HTTP, Optional HTTPS)___ - This must match the Subdomain you entered on the Web Push settings on the OneSignal dashboard. - __`Boolean` _autoRegister (Optional, Available for HTTPS only)___ -Default true. Automatically show browser prompt to accept notifications. You can pass in false to delay this pop-up and then call `registerForPushNotifications` to prompt them later. Only works for HTTPS. - __`String` _path (Available For HTTPS only)___ - Normally you will want to set as "/" to indicate your OneSignalSDKWorker.js and OneSignalSDKUpdaterWorker.js are at the root of your domain. Example https://yourdomain.com/OneSignalSDKUpdaterWorker.js and https://yourdomain.com/OneSignalSDKUpdaterWorker.js should both be accessible. - __`JSON` _promptOptions (Optional)___ - Use these parameters to localize the HTTP popup prompt to your custom text and language. All entries are limited in length. Foreign characters accepted. Each parameter is optional, and its default is used when it is not included. - __`String` _actionMessage (Optional)___ - Text that says 'wants to show notifications' by default. Limited to 75 characters. - __`String` _exampleNotificationTitleDesktop (Optional)___ - Text that says 'This is an example notification'. Displays on non-mobile devices. Only one line is allowed. - __`String` _exampleNotificationMessageDesktop (Optional)___ - Text that says 'Notifications will appear on your desktop'. Displays on non-mobile devices. Only one line is allowed. - __`String` _exampleNotificationTitleMobile (Optional)___ - Text that says 'This is an example notification'. Displays on mobile devices with limited screen width. Only one line is allowed. - __`String` _exampleNotificationMessageMobile (Optional)___ - Text that says 'Notifications will appear on your device'. Displays on mobile devices with limited screen width. Only one line is allowed. - __`String` _exampleNotificationCaption (Optional)___ - Text that says '(you can unsubscribe anytime)'. - __`String` _acceptButtonText (Optional)___ - Text that says 'CONTINUE'. - __`String` _cancelButtonText (Optional)___ - Text that says 'NO THANKS'. - __`Boolean` _showCredit (Optional)___ - Set to false to hide the OneSignal logo. - __`JSON` _welcomeNotification (Optional)___ - Use these parameters to customize or disable the welcome notification sent to new site visitors. Any person visiting your site for their first time, or an existing user who has completely cleared their cache is considered a new site visitor. - __`Boolean` _disable (Optional)___ - Disables sending a welcome notification to new site visitors. If you want to disable welcome notifications, this is the only option you need. - __`String` _title (Optional)___ - The welcome notification's title. You can localize this to your own language. If not set, or left blank, the site's title will be used. Set to one space ' ' to clear the title, although this is not recommended. - __`String` _message (Required)___ - The welcome notification's message. You can localize this to your own language. A message is required. If left blank or set to blank, the default of 'Thanks for subscribing!' will be used. - __`JSON` _notifyButton (Optional)___ - Use these parameters to enable and customize the notifyButton. All parameters below are optional. If not set, they will be replaced with their defaults. - __`Boolean` _enable___ - Enable the notify button. The notify button is otherwise disabled by default. - __`String` _size___ - One of 'small', 'medium', or 'large'. The notify button will initially appear at one of these sizes, and then shrink down to size 'small' after the user subscribes. - __`String` _position___ - Either 'bottom-left' or 'bottom-right'. The notify button will be fixed at this location on your page. - __`JSON` _offset___ - Specify CSS-valid pixel offsets using bottom, left, and right. - __`Boolean` _modalPrompt___ - If you use the modal prompt for your HTTPS website, you should specify it here too so the bell shows the modal instead of the popup. - __`Boolean` _prenotify___ - If true, the notify button will display an icon that there is 1 unread message. When hovering over the notify button, the user will see custom text set by `message.prenotify`. - __`Boolean` _showCredit___ - Set false to hide the 'Powered by OneSignal' text in the notify button dialog popup. - __`JSON` _text___ - Customize the notify button text. See the example code below to know what to change. - __`Boolean` _persistNotification (Optional)___ - Applies only on Chrome Desktop 47+. If false, the notification will disappear roughly after 20 seconds. If true, the notification will be displayed indefinitely until the user interacts with the notification (dismisses it or clicks it). If this optional value is not set, it defaults to true (i.e. notifications by default persist indefinitely). On Firefox and Safari, notifications automatically dismiss after some time and this parameter does not control that. - __`JSON` _webhooks (Optional)___ - See our [Webhooks page](doc:webhooks) for the nested options. **Simple Example** The following is a basic template of how you would call init(). [See our Customizing Features page to see additional examples.](doc:customizing-features) [block:code] { "codes": [ { "code": "// OneSignal is defined as an array here and uses push calls to support OneSignalSDK.js being loaded async.\nvar OneSignal = OneSignal || [];\n\nOneSignal.push([\"init\", {\n appId: \"YOUR_APP_ID\",\n // Your other init settings\n}]);", "language": "javascript" } ] } [/block] [block:html] { "html": "<br><a name=\"registerForPushNotifications\">" } [/block] ## registerForPushNotifications() Prompts the user to subscribe to your site's notifications, or if the user has already subscribed, does nothing. For HTTPS sites, the native browser subscription prompt is displayed. For HTTP sites, a popup prompt is displayed instead. See the `subscriptionChange` event to know when the user has successfully subscribed. __Parameters__ - __`JSON` _options(Optional)___ - __`Boolean` _modalPrompt (Optional)___ - Shows a modal popup window on your page explaining and showing an example notification with an option to continue or cancel before showing the native notification prompt to accept notifications. * (Option is only available for HTTPS when not using a subdomain. Otherwise a popup window will show with the same results.)* __Example__ [block:code] { "codes": [ { "code": "OneSignal.push([\"registerForPushNotifications\"]);\n// Optional: OneSignal.push([\"registerForPushNotifications\", {modalPrompt: true}]);", "language": "javascript" } ] } [/block] [block:html] { "html": "<br><a name=\"setDefaultNotificationUrl\">" } [/block] ## setDefaultNotificationUrl(url) Pass in the full URL of the default page you want to open when a notification is clicked. - __Parameters__ - __`String` _url___ - page url to open from notifications __Example__ [block:code] { "codes": [ { "code": "OneSignal.push([\"setDefaultNotificationUrl\", \"https://domain.com/index2\"]);", "language": "javascript" } ] } [/block] [block:html] { "html": "<br><a name=\"setDefaultIcon\">" } [/block] [block:html] { "html": "<br><a name=\"setDefaultTitle\">" } [/block] ## setDefaultTitle(title) Sets the default title to display on notifications. Will default to the page's `document.title` if you don't call this. - __Parameters__ - __`String` _title___ - String to set as a default title on notifications __Example__ [block:code] { "codes": [ { "code": "OneSignal.push([\"setDefaultTitle\", \"Custom Default Title\"]);", "language": "javascript" } ] } [/block] [block:html] { "html": "<br><a name=\"sendTag\">" } [/block] ## sendTag (key, value, callback) Tag a user based on an app event of your choosing so later you can create segments on [onesignal.com](https://onesignal.com) to target these users. Recommend using sendTags over sendTag if you need to set more than one tag on a user at a time. You can call `OneSignal.push(["sendTag", "key", "value"])` anytime after `var OneSignal = OneSignal || [];`; you do not have to wait until the user registers. Once the user registers, the tags will automatically be sent to our server as long as the page session is the same (i.e. the user has not navigated to another page). - __Parameters__ - __`string` _key___ - Key of your choosing to create or update. - __`string` _value___ - Value to set on the key. - _NOTE:_ Passing in a blank String deletes the key, you can also call deleteTag. - __`Function` _callback___ - Call back to be fired when the tags have been sent to our server and a response has been returned. The first parameter of the callback is an object of the tags you sent (key-value pairs). Returns a `Promise` that is resolved with the object key-pairs of the tags you sent, or rejected with an error. __Example__ [block:code] { "codes": [ { "code": "OneSignal.push([\"sendTag\", \"key\", \"value\", function(tagsSent) {\n // Callback called when tags have finished sending\n}]);", "language": "javascript" } ] } [/block] [block:html] { "html": "<br><a name=\"sendTags\">" } [/block] ## sendTags(keyValues, callback) Tag a user based on an app event of your choosing so later you can create segments on [onesignal.com](https://onesignal.com) to target these users. You can call `OneSignal.push(["sendTags", {key2: "value2", key3: "value3"}])` anytime after `var OneSignal = OneSignal || [];`; you do not have to wait until the user registers. Once the user registers, the tags will automatically be sent to our server. - __Parameters__ - __`JSON` _keyValues___ - Key value pairs of your choosing to create or update. - _NOTE:_ Passing in a blank String as a value deletes the key, you can also call deleteTag or deleteTags. - __`Function` _callback___ - Call back to be fired when the tags have been sent to our server and a response has been returned. The first parameter of the callback is an object of the tags you sent (key-value pairs). Returns a `Promise` that is resolved with the object key-pairs of the tags you sent, or rejected with an error. __Example__ [block:code] { "codes": [ { "code": "OneSignal.push([\"sendTags\", {key2: \"value2\", key3: \"value3\"}, function() {\n // Callback called when tags have finished sending \n}]);", "language": "javascript" } ] } [/block] [block:html] { "html": "<br><a name=\"getTags\">" } [/block] ## getTags(callback) Retrieve a list of tags that have been set on the user from the OneSignal server. - __Parameters__ - __`Function` _callback___ - Callback to be fired when the list of tags has been retrieved. The first parameter of the callback is an object containing key-value pairs of the tags. Returns a `Promise` that is resolved with the object key-pairs of the tags you sent, or rejected with an error. __Example__ [block:code] { "codes": [ { "code": "OneSignal.push([\"getTags\", function(tags) {\n\t\tconsole.log(\"OneSignal getTags:\", tags);\n\t}]);", "language": "javascript" } ] } [/block] [block:html] { "html": "<br><a name=\"deleteTag\">" } [/block] ## deleteTag(key) Deletes a tag that was previously set on a user with `sendTag` or `sendTags`. Use `deleteTags` if you need to delete more than one. - __Parameters__ - __`String` _key___ - Key to remove. Returns a `Promise` that is resolved with the object key-pair of the tag you deleted, or rejected with an error. __Example__ [block:code] { "codes": [ { "code": "OneSignal.push([\"deleteTag\", \"key\"]);", "language": "javascript" } ] } [/block] [block:html] { "html": "<br><a name=\"deleteTags\">" } [/block] ## deleteTags(keys, callback) Deletes tags that were previously set on a user with `sendTag` or `sendTags`. - __Parameters__ - __`Array` _keys___ - Keys to remove. - __`Function` _callback___ - Callback to be fired when the list of tags has been removed. The first parameter of the callback is an array of the tags that were deleted. Returns a `Promise` that is resolved with the object key-pairs of the tags you deleted, or rejected with an error. __Example__ [block:code] { "codes": [ { "code": "OneSignal.push([\"deleteTags\", [\"key1\", \"key2\"]]);", "language": "javascript" } ] } [/block] [block:html] { "html": "<br><a name=\"isPushNotificationsEnabled\">" } [/block] ## isPushNotificationsEnabled() Passes true to the passed in callback if the user has already accepted push notifications and successfully registered with Google's GCM server and OneSignal's server. Callback should fire within 1 second so you can change your page to reflect if notifications are enabled or not. Use [getIdsAvailable](#getIdsAvailable) you if want to only to run code after/if the user accepts push notifications and registers successfully. - __Parameters__ - __`function` _isPushNotificationsEnabledCallBack___ - Passed in function which will receive one boolean parameter if they are enabled or not. [block:code] { "codes": [ { "code": "OneSignal.push([\"isPushNotificationsEnabled\", function(enabled) {\n\tif (enabled)\n console.log(\"Push notifications are enabled!\");\n else\n console.log(\"Push notifications are not enabled yet.\");\n}]);", "language": "javascript" } ] } [/block] [block:html] { "html": "<br><a name=\"isPushNotificationsSupported\">" } [/block] ## isPushNotificationsSupported() Returns true if the current browser viewing the page supports push notifications. [block:code] { "codes": [ { "code": "OneSignal.push(function() {\n\tif (OneSignal.isPushNotificationsSupported())\n console.log(\"Push notifications are supported, please allow the permission to enable them\");\n});", "language": "javascript" } ] } [/block] [block:html] { "html": "<br><a name=\"getUserId\">" } [/block] ## getUserId() Returns a Promise that resolves to the stored OneSignal user ID if one is set, otherwise the Promise resolves to null. For custom implementations involving our REST API, associate this OneSignal user ID with your data. Once created, the user ID will not change. If the user unsubscribes from web push, for example by clearing their browser data, and resubscribes, a new user ID will be created and a new entry will be stored on your app's users list. The old entry will not be automatically deleted. - __Parameters__ - __`function` _callback___ - A callback function which sets the first parameter to the stored OneSignal user ID if one is set, otherwise the first parameter is set to null. __Example__ [block:code] { "codes": [ { "code": "OneSignal.push([\"getUserId\", function(userId) {\n console.log(\"OneSignal User ID:\", userId);\n // (Output) OneSignal User ID: 270a35cd-4dda-4b3f-b04e-41d7463a2316\n}]);", "language": "javascript" } ] } [/block] [block:html] { "html": "<br><a name=\"getRegistrationId\">" } [/block] ## getRegistrationId() Returns a Promise that resolves to the stored OneSignal registration ID if one is set, otherwise the Promise resolves to null. For custom implementations involving our REST API, use the above OneSignal user ID with your data instead of this registration ID. The registration ID is the device token associated with GCM or Apple's push notification server. It is an internal ID we use to generate the corresponding OneSignal user ID. We do not recommend using or storing the registration ID unless necessary. - __Parameters__ - __`function` _callback___ - A callback function which sets the first parameter to the stored OneSignal registration ID if one is set, otherwise the first parameter is set to null. __Example__ [block:code] { "codes": [ { "code": "OneSignal.push([\"getRegistrationId\", function(registrationId) {\n console.log(\"OneSignal Registration ID:\", registrationId);\n // (Output) OneSignal Registration ID: cPMqRjFKn6U:APA91bGgr5-3ny36bQxBCA7uAoQIDsUtX6q7CL4FcsDiHlGgDh471C8cEktPYzTsO2OaOCeZmB0gLSSErzwM3fcZWI9LFkW8LEQzBVw7UbQ8NtlBF0dTADoYLF87xXSztUjAkFLP5_Vy\n}]);", "language": "javascript" } ] } [/block] [block:html] { "html": "<br><a name=\"getNotificationPermission\">" } [/block] ## getNotificationPermission() Returns a Promise that resolves to the browser's current notification permission as 'default', 'granted', or 'denied'. You can use this to detect whether the user has allowed notifications, blocked notifications, or has not chosen either setting. - __Parameters__ - __`function` _callback___ - A callback function that will be called when the browser's current notification permission has been obtained, with one of 'default', 'granted', or 'denied'. __Example__ [block:code] { "codes": [ { "code": "OneSignal.push([\"getNotificationPermission\", function(permission) {\n console.log(\"Site Notification Permission:\", permission);\n // (Output) Site Notification Permission: default\n}]);", "language": "javascript" } ] } [/block] [block:html] { "html": "<br><a name=\"addListenerForNotificationOpened\">" } [/block] ## addListenerForNotificationOpened(callback) Passed in callback that fires when the user clicks on a OneSignal notification. Please see the [callback documentation](https://documentation.onesignal.com/docs/website-sdk-api#section-notificationopenedcallback) as specific cases are required to trigger this event. - __Parameters__ - __`function` _notificationOpenedCallBack___ - Passed in function which will receive one parameter containing JSON with data about the notification that was clicked. __Example__ [block:code] { "codes": [ { "code": "OneSignal.push([\"addListenerForNotificationOpened\", function(data) {\n\tconsole.log(\"Received NotificationOpened:\");\n\tconsole.log(data);\n}]);", "language": "javascript" } ] } [/block] <br><div id="setSubscription "> ## setSubscription(optOut) OneSignal.setSubscription() is used to temporarily opt-out the user from receiving notifications by setting a flag on our system so that notifications are not delivered to the user. Set to false to temporarily "mute" notifications from going to the user. If you previously set this to false, you can set it to true to "un-mute" notifications so that the user receives them again. **This event is not related to actually prompting the user to subscribe. The user must already be subscribed.** - __Parameters__ - __`boolean` _enable___ __Example__ [block:code] { "codes": [ { "code": "OneSignal.push([\"setSubscription\", false]);", "language": "javascript" } ] } [/block] [block:html] { "html": "<br/><a name=\"sendSelfNotification\">" } [/block] ## sendSelfNotification(title, message, url, icon, data) Sends a push notification to the current user on the webpage. This is a simplified utility function to send a test message to yourself or a quick message to the user. It does not support any targeting options. - __Parameters__ - __`String` _title___ - The notification's title. Currently defaults to "OneSignal Test Message" if not set. Use a " " single space to get around this. Multiple languages are not supported; write the text in the language the current user should receive it in. - __`String` _message___ - The notification's body content. Required. Multiple languages are not supported; write the text in the language the current user should receive it in. - __`String` _url___ - The URL to launch when the notification is clicked.[ Use a special URL to prevent any URL from launching](https://documentation.onesignal.com/docs/web-push-action-buttons#how-can-i-prevent-the-action-button-from-opening-a). Defaults to this special URL if none is set. - __`String` _icon___ - The URL to use for the notification icon. - __`Hash` _data___ - Additional data to pass for the notification. - __`Array of Hash` _buttons___ - See [Action Buttons](doc:web-push-action-buttons) docs. - __Example__ [block:code] { "codes": [ { "code": "OneSignal.sendSelfNotification(\n /* Title (defaults if unset) */\n \"OneSignal Web Push Notification\",\n /* Message (defaults if unset) */\n \"Action buttons increase the ways your users can interact with your notification.\", \n /* URL (defaults if unset) */\n 'https://example.com/?_osp=do_not_open',\n /* Icon */\n 'https://onesignal.com/images/notification_logo.png',\n {\n /* Additional data hash */\n notificationType: 'news-feature'\n }, \n [{ /* Buttons */\n /* Choose any unique identifier for your button. The ID of the clicked button is passed to you so you can identify which button is clicked */.\n id: 'like-button',\n /* The text the button should display. Supports emojis. */\n text: 'Like',\n /* A valid publicly reachable URL to an icon. Keep this small because it's downloaded on each notification display. */\n icon: 'http://i.imgur.com/N8SN8ZS.png',\n /* The URL to open when this action button is clicked. See the sections below for special URLs that prevent opening any window. */\n url: 'https://example.com/?_osp=do_not_open'\n },\n {\n id: 'read-more-button',\n text: 'Read more',\n icon: 'http://i.imgur.com/MIxJp1L.png',\n url: 'https://example.com/?_osp=do_not_open'\n }]\n);", "language": "javascript" } ] } [/block] [block:html] { "html": "<br/><a name=\"showHttpPrompt\">" } [/block] ## showHttpPrompt() Shows a prompt for HTTP site users to subscribe to notifications. Please see [HTTP Prompt](doc:web-push-http-prompt) for more details. __Example__ [block:code] { "codes": [ { "code": "OneSignal.showHttpPrompt();", "language": "javascript" } ] } [/block] [block:html] { "html": "<br><br><br>" } [/block] [block:api-header] { "type": "basic", "title": "Events" } [/block] [block:html] { "html": "<a name=\"subscriptionChangeEvent\">" } [/block] #### Subscription Change Event Occurs when the user's subscription state changes between unsubscribed and subscribed. On Chrome and Firefox, the user's subscription is true when: - Your site is granted notification permissions - Your site visitor's web storage database containing OneSignal-related data is intact - You have not manually opted out the user from receiving notifications - The notify button's 'Subscribe' and 'Unsubscribe' button opts users in and out without affecting their other subscription parameters - `OneSignal.setSubscription()` is used to opt the user in and out - Your site visitor has an installed background web worker used to display notifications On Safari, only the first three are required for a valid subscription. Use this event to find out when the user has successfully subscribed. The parameter will be set to true to represent a new subscribed state. A user is no longer subscribed if: - The user changes notification permissions - The icon next to the URL in the address bar can be clicked to modify site permissions - Chrome and Firefox notifications come with a button on the notification to block site notifications - The user clears their browser data (clearing cookies will not effect subscription) - Another background web worker overwrites our web worker This event *is not related* to `OneSignal.setSubscription()`. `OneSignal.setSubscription()` is used to temporarily opt-out the user from receiving notifications by setting a flag on our system so that notifications are not delivered to the user. This event is more like an event for when `OneSignal.isPushNotificationsEnabled()` changes. - __Callback Event Parameters__ - __`Boolean` _subscribed___ - Set to true if the user is currently subscribed; otherwise set to false. __Example__ [block:code] { "codes": [ { "code": "OneSignal.push(function() {\n // Occurs when the user's subscription changes to a new value.\n OneSignal.on('subscriptionChange', function (isSubscribed) {\n console.log(\"The user's subscription state is now:\", isSubscribed);\n });\n});", "language": "javascript" } ] } [/block] [block:html] { "html": "<a name=\"notificationDisplayEvent\">" } [/block] ## Notification Display Event Occurs after a notification is visibly displayed on the user's screen. Supported On: Chrome and Firefox, not supported on Safari. This event is fired on your page. If multiple browser tabs are open to your site, this event will be fired on *all* pages on which OneSignal is active. - __Callback Event Parameters__ - __`Hash` _event___ - A JavaScript object hash containing: - __`UUID` _id___ - The OneSignal notification ID of the notification that was just displayed. - __`String` _heading___ - The notification's title. - __`String` _content___ - The notification's body message, not including the title. - __`String` _url___ - The URL that will be opened if the user clicks on the notification. - __`String` _icon___ - The URL to the icon used for the notification. This is fetched every time the notification is displayed. Note: Depending on the notification, more fields (e.g. action buttons) can be included in the callback parameter. __Example__ [block:code] { "codes": [ { "code": "OneSignal.on('notificationDisplay', function (event) {\n\tconsole.warn('OneSignal notification displayed:', event);\n /*\n {\n \"id\": \"ce31de29-e1b0-4961-99ee-080644677cd7\",\n \"heading\": \"OneSignal Test Message\",\n \"content\": \"This is an example notification.\",\n \"url\": \"https://onesignal.com?_osp=do_not_open\",\n \"icon\": \"https://onesignal.com/images/notification_logo.png\"\n }\n */\n});", "language": "javascript" } ] } [/block] [block:html] { "html": "<a name=\"notificationDismissEvent\">" } [/block] ## Notification Dismiss Event This event occurs when: - A user purposely dismisses the notification without clicking the notification body or action buttons - On Chrome on Android, a user dismisses all web push notifications (this event will be fired for each web push notification we show) - A notification expires on its own and disappears **Note:** This event *does not occur* if a user clicks on the notification body or one of the action buttons. That is considered a notification click (please see the `addListenerForNotificationOpened` method). Supported On: Chrome 50+ only. This event is fired on your page. If multiple browser tabs are open to your site, this event will be fired on *all* pages on which OneSignal is active. - __Callback Event Parameters__ - __`Hash` _event___ - A JavaScript object hash containing: - __`UUID` _id___ - The OneSignal notification ID of the notification that was just displayed. - __`String` _heading___ - The notification's title. - __`String` _content___ - The notification's body message, not including the title. - __`String` _url___ - The URL that will be opened if the user clicks on the notification. - __`String` _icon___ - The URL to the icon used for the notification. This is fetched every time the notification is displayed. Note: Depending on the notification, more fields (e.g. action buttons) can be included in the callback parameter. __Example__ [block:code] { "codes": [ { "code": "OneSignal.on('notificationDismiss', function (event) {\n\tconsole.warn('OneSignal notification dismissed:', event);\n /*\n {\n \"id\": \"ce31de29-e1b0-4961-99ee-080644677cd7\",\n \"heading\": \"OneSignal Test Message\",\n \"content\": \"This is an example notification.\",\n \"url\": \"https://onesignal.com?_osp=do_not_open\",\n \"icon\": \"https://onesignal.com/images/notification_logo.png\"\n }\n */\n});", "language": "javascript" } ] } [/block] [block:api-header] { "type": "basic", "title": "Callbacks" } [/block] [block:html] { "html": "<a name=\"tagsReceivedCallBack\">" } [/block] ## tagsReceivedCallBack Gets all the tags set on a user from onesignal.com. - __Parameters__ - __`JSON` _tags___ - JSON object of key value pairs retrieved from the OneSignal server. __Example__ [block:code] { "codes": [ { "code": "OneSignal.push([\"getTags\", function(tags) {\n\t\tconsole.log(\"OneSignal getTags:\");\n\t\tconsole.log(tags);\n\t}]);", "language": "javascript" } ] } [/block] [block:html] { "html": "<br><a name=\"notificationOpenedCallBack\">" } [/block] ## notificationOpenedCallBack **Note:** This functionality is only supported by Chrome and Firefox, not Safari. Occurs when a notification is clicked that opens a URL back to your page with the OneSignal SDK. **By default:** Suppose the notification opens the URL "https://yoursite.com/a/b/c/". If an existing tab is already open to the *same exact* URL, that tab will be focused and receive the callback. If no existing tab matching *the exact same URL* is open, a new browser tab will be opened and this newly opened tab will receive fire the notificationOpenedCallBack. If multiple existing tabs *all matching exactly the URL* of the notification are already open, one of the tabs will receive the callback. **Alternatively:** In the OneSignal web SDK init options, you can set `notificationClickHandlerMatch` to the literal string `"origin"`. This relaxes the matching restriction above so that existing browser tabs on your site don't need to exactly match the notification URL to be focused. With this flag set, suppose the notification opens the URL "https://yoursite.com/a/b/c". If you have any browser tab open to "https://yoursite.com", for example "https://yoursite.com/zzz", then the tab with "https://yoursite.com/zzz" or "https://yoursite.com" will be focused and will receive the callback. Any tab that *matches your origin* will receive the callback. *Note*: While the above is true for HTTPS sites (*any* tab that matches the origin will be focusable), for HTTP sites, the existing tab must be running the OneSignal SDK to catch the focus event from our background worker. For HTTPS sites this restriction is not necessary. This mode is useful for single-page apps that want to catch the event and handle their own redirection. An *origin* is a combination of protocol, hostname, and port. https://domain.com is not the same origin as https://www.domain.com. This callback accepts one parameter, which is a JavaScript object containing the details of the notification, as listed below: - __JSON__ - __`String` _id___ - The OneSignal notification ID of the notification that was just clicked. - __`String` _heading___ - Title set on the notification. - __`String` _content___ - The message text the user seen in the notification. - __`String` _icon___ - Icon set on the notification. - __`String` _url___ - The URL that this notification opened. - __`JSON` _data___ - Key value pairs that were set on the notification. - __`String` _action___ - Describes whether the notification body was clicked or one of the action buttons (if present) was clicked. An empty string means the notification body was clicked, otherwise the string is set to the action button ID. __Example__ [block:code] { "codes": [ { "code": "/* Do NOT call init twice */\nOneSignal.push([\"init\", {\n /* Your other init settings ... */\n notificationClickHandlerMatch: 'origin', /* See above documentation: 'origin' relaxes tab matching requirements *.\n /* ... */\n}]);", "language": "javascript" } ] } [/block] [block:code] { "codes": [ { "code": "OneSignal.push([\"addListenerForNotificationOpened\", function(data) {\n\tconsole.log(\"Received NotificationOpened:\", data);\n}]);", "language": "javascript" } ] } [/block] [block:api-header] { "type": "basic", "title": "Deprecations" } [/block] March 15, 2016: Deprecated `getIdsAvailable()` in favor of `getUserId()` and `getRegistrationId()`. Deprecated `idsAvailableCallback` in favor of `subscriptionChange` event.