### Add User Tag (Example) Source: https://github.com/onesignal/onesignal-website-sdk/blob/main/MIGRATION_GUIDE.md Example of adding a tag to a user. This call must be invoked after SDK initialization and is not supported in HTTP or AMP environments. ```javascript OneSignal.User.addTag("tag", "2"); ``` -------------------------------- ### Run Preview Builds with Vite Source: https://github.com/onesignal/onesignal-website-sdk/blob/main/preview/README.md Navigate to the preview directory and run the desired script to build the SDK and start the Vite development server. These scripts allow testing against different OneSignal API environments. ```bash cd preview vp run start # alias for start:dev vp run start:dev # local SDK against the production OneSignal API vp run start:dev-stag # local SDK against staging (API_TYPE=staging, API_ORIGIN=onesignal.com) ``` -------------------------------- ### Alias Example in JavaScript Object Source: https://github.com/onesignal/onesignal-website-sdk/blob/main/MIGRATION_GUIDE.md Shows how to represent user aliases as a JavaScript object, mapping alias labels directly to their IDs. ```javascript // WebSDK-specific example { external_id: "1234", my_alias: "5678" } ``` -------------------------------- ### Mock HTTP GET Request with msw Source: https://github.com/onesignal/onesignal-website-sdk/blob/main/TESTS.md Mock HTTP requests using msw. This example shows how to mock a GET request to the notifications endpoint. ```typescript import { server } from '__test__/support/mocks/server'; import { http, HttpResponse } from 'msw'; server.use( http.get('https://api.onesignal.com/notifications', () => HttpResponse.json({ result: {}, status: 200 }), ), ); // or server.use(http.get('**/v1/notifications', () => HttpResponse.json({ result: {}, status: 200 }))); ``` -------------------------------- ### Alias Example in JSON Source: https://github.com/onesignal/onesignal-website-sdk/blob/main/MIGRATION_GUIDE.md Illustrates the structure for defining user aliases using JSON format, including 'external_id' and custom labels. ```json { "aliases": [ { "label": "external_id", "id": "1234" }, { "label": "my_alias", "id": "5678" } ] } ``` -------------------------------- ### Example Service Worker Update Logic Source: https://github.com/onesignal/onesignal-website-sdk/wiki/Set-up-web-push-on-a-custom-HTTPS-subdomain This JavaScript code demonstrates how a server might respond to requests for the OneSignal service worker, ensuring updates by returning the SDK script with a different query parameter each time. This is crucial for maintaining the latest version of the web SDK. ```javascript importScripts('https://cdn.onesignal.com/sdks/OneSignalSDK.js?v=1'); importScripts('https://cdn.onesignal.com/sdks/OneSignalSDK.js?v=2'); importScripts('https://cdn.onesignal.com/sdks/OneSignalSDK.js?v=3'); importScripts('https://cdn.onesignal.com/sdks/OneSignalSDK.js?v=4'); importScripts('https://cdn.onesignal.com/sdks/OneSignalSDK.js?v=5'); ``` -------------------------------- ### Get Notification Permission Status Source: https://github.com/onesignal/onesignal-website-sdk/blob/main/MIGRATION_GUIDE.md Retrieves the browser's native notification permission status. Possible values are "default", "granted", or "denied". ```javascript OneSignal.permissionNative; ``` -------------------------------- ### JavaScript to Get Safari Push Notification Permission Source: https://github.com/onesignal/onesignal-website-sdk/wiki/What-happens-if-...? This JavaScript code snippet is used to check the permission status and retrieve the device token for Safari push notifications. It requires the correct website push ID. ```javascript window.safari.pushNotification.permission('web.com.pushassist.push') ``` ```javascript window.safari.pushNotification.permission('web.onesignal.auto.115f8fcb-d4e8-44f7-85e0-0f5ff0e5093f') ``` ```javascript window.safari.pushNotification.permission('web.onesignal.auto.1b1338f0-ae7a-49c0-a5a1-0112be9b9bea') ``` -------------------------------- ### Build OneSignal Web SDK Source: https://github.com/onesignal/onesignal-website-sdk/blob/main/preview/README.md Build the SDK from the repository root using predefined environment configurations. You can specify build and API environments independently. ```bash vp run build: # Where is dev, staging, or prod. vp run build:- # Example: builds with BUILD environment as development and API environment as production. ``` -------------------------------- ### AMP Web Push Initialization for Multiple Subdomains Source: https://github.com/onesignal/onesignal-website-sdk/wiki/AMP-Advanced-Setup Use this HTML code within the of your AMP page to initialize AMP web push when managing multiple legacy subdomains. Ensure 'YOURDOMAIN.COM' and 'YOUR-APP-ID' are replaced with your actual domain and OneSignal App ID. ```html ``` -------------------------------- ### Initialize OneSignal Web SDK with Custom Settings Source: https://github.com/onesignal/onesignal-website-sdk/blob/main/preview/index.html Initializes the OneSignal SDK with a specific App ID, welcome notification settings, service worker configuration, and custom prompt options including categories and custom links. ```javascript var OneSignalDeferred = window.OneSignalDeferred || []; OneSignalDeferred.push(async function (onesignal) { await onesignal.init({ appId: appId, welcomeNotification: { disable: false, title: 'Custom Welcome Notification Title', message: 'Custom Welcome Notification Message', url: 'https://example.com' }, serviceWorkerParam: { scope: '/' + SERVICE_WORKER_PATH }, serviceWorkerPath: SERVICE_WORKER_PATH + 'OneSignalSDKWorker.js', notifyButton: { enable: true, }, promptOptions: { slidedown: { prompts: [ { type: 'category', autoPrompt: false, categories: [ { tag: 'politics', label: 'Politics' }, { tag: 'usa_news', label: 'USA News' }, { tag: 'world_news', label: 'World News' }, { tag: 'culture', label: 'Culture' }, { tag: 'technology', label: 'Technology' }, { tag: 'fashion', label: 'Fashion' }, { tag: 'art', label: 'Art' }, { tag: 'long_category', label: 'Very Long Category' } ] }, { type: 'sms', autoPrompt: false }, { type: 'email', autoPrompt: false }, { type: 'smsAndEmail', autoPrompt: false } ] } }, customlink: { enabled: true /* Required to use the Custom Link */, style: 'button' /* Has value of 'button' or 'link' */, size: 'medium' /* One of 'small', 'medium', or 'large' */, color: { button: '#e54b4d' /* Color of the button background if style = "button" */, text: '#FFFFFF' /* Color of the prompt's text */ }, text: { subscribe: 'Subscribe to push notifications' /* Prompt's text when not subscribed */, unsubscribe: 'Unsubscribe from push notifications' /* Prompt's text when subscribed */, explanation: 'Get updates from all sorts of things that matter to you' /* Optional text appearing before the prompt button */ }, unsubscribeEnabled: true /* Controls whether the prompt is visible after subscription */ } }); }); ``` -------------------------------- ### Display SMS and Email Subscription Prompts Source: https://github.com/onesignal/onesignal-website-sdk/blob/main/MIGRATION_GUIDE.md Asynchronously displays prompts for users to subscribe to both SMS and email notifications. Accepts an options object for configuration. ```javascript await OneSignal.Slidedown.promptSmsAndEmail(); ``` -------------------------------- ### Basic Test File Structure Source: https://github.com/onesignal/onesignal-website-sdk/blob/main/TESTS.md A template for a basic test file using Vitest. It includes mocking a file and setting up test environment hooks. ```typescript import { TestEnvironment } from '../../support/environment/TestEnvironment'; // mock an entire file vi.mock('../../../src/MyFile'); describe('My tests', () => { beforeEach(() => { TestEnvironment.initialize(); }); afterEach(() => { vi.resetAllMocks(); }); test('This is a test description', () => {}); }); ``` -------------------------------- ### Customize Build and API Origins Source: https://github.com/onesignal/onesignal-website-sdk/blob/main/preview/README.md Override the default build and API origins using environment variables. Ensure custom origins are compatible with the selected build and API environments. ```bash API_ORIGIN=texas vp run build:dev-prod # Sets the BUILD environment origin to texas (so SDK files are fetched from https://texas:4001/sdks/web/v##/) # and the API environment origin to production (so all OneSignal API calls go to https://api.onesignal.com/apps/). BUILD_ORIGIN=localhost API_ORIGIN=texas vp run build:dev-dev # Sets the BUILD origin to localhost (SDK files from https://localhost:4001/sdks/web/v##/) # and the API origin to https://texas:3001/api/v1/apps/. ``` -------------------------------- ### Display Email Subscription Prompt Source: https://github.com/onesignal/onesignal-website-sdk/blob/main/MIGRATION_GUIDE.md Asynchronously displays a prompt for users to subscribe to email notifications. Accepts an options object for configuration. ```javascript await OneSignal.Slidedown.promptEmail(); ``` -------------------------------- ### Display Push Categories Prompt Source: https://github.com/onesignal/onesignal-website-sdk/blob/main/MIGRATION_GUIDE.md Asynchronously displays a prompt for users to subscribe to notification categories. Accepts an options object for configuration. ```javascript await OneSignal.Slidedown.promptPushCategories(); ``` -------------------------------- ### Disable HTTPS for Preview Server Source: https://github.com/onesignal/onesignal-website-sdk/blob/main/preview/README.md Run the preview server using HTTP instead of HTTPS by setting the HTTPS environment variable to false. This changes the default port from 4001 to 4000. ```bash HTTPS=false vp run build:dev-prod # The preview server itself also accepts HTTPS=false to bind HTTP on port 4000 instead of HTTPS on 4001: HTTPS=false vp run start ``` -------------------------------- ### Configure Hosts Alias for Local Backend Source: https://github.com/onesignal/onesignal-website-sdk/blob/main/preview/README.md Add a hosts alias to your /etc/hosts file to map a domain name to your local OneSignal backend IP address. This is necessary when the backend is running on a different machine. ```bash # file: /etc/hosts 192.168.40.21 texas ``` -------------------------------- ### Display Push Notification Prompt Source: https://github.com/onesignal/onesignal-website-sdk/blob/main/MIGRATION_GUIDE.md Asynchronously displays the native browser prompt to ask the user for permission to send push notifications. Accepts an options object for configuration. ```javascript await OneSignal.Slidedown.promptPush(); ``` -------------------------------- ### Display SMS Subscription Prompt Source: https://github.com/onesignal/onesignal-website-sdk/blob/main/MIGRATION_GUIDE.md Asynchronously displays a prompt for users to subscribe to SMS notifications. Accepts an options object for configuration. ```javascript await OneSignal.Slidedown.promptSms(); ``` -------------------------------- ### Slidedown Namespace Source: https://github.com/onesignal/onesignal-website-sdk/blob/main/MIGRATION_GUIDE.md Offers methods to display various subscription prompts to users, including push notifications, SMS, and email. ```APIDOC ## Slidedown Namespace ### Description Offers methods to display various subscription prompts to users, including push notifications, SMS, and email. ### Methods #### `promptPush(options: AutoPromptOptions)` - **Description**: Displays the notification permission prompt. - **Sync/Async**: `async` #### `promptPushCategories(options: AutoPromptOptions)` - **Description**: Displays the notification permission prompt for notification categories. - **Sync/Async**: `async` #### `promptSms(options: AutoPromptOptions)` - **Description**: Displays the SMS subscription prompt. - **Sync/Async**: `async` #### `promptEmail(options: AutoPromptOptions)` - **Description**: Displays the email subscription prompt. - **Sync/Async**: `async` #### `promptSmsAndEmail(options: AutoPromptOptions)` - **Description**: Displays the SMS and email subscription prompts. - **Sync/Async**: `async` #### `addEventListener(event: "slidedownShown", listener: (wasShown: boolean) => void)` - **Description**: Adds an event listener for the `slidedownShown` event. - **Sync/Async**: `sync` #### `removeEventListener(event: "slidedownShown", listener: (wasShown: boolean) => void)` - **Description**: Removes an event listener for the `slidedownShown` event. - **Sync/Async**: `sync` ``` -------------------------------- ### PushAssist Safari Push Package Configuration Source: https://github.com/onesignal/onesignal-website-sdk/wiki/What-happens-if-...? This JSON object represents the configuration for a Safari push package provided by PushAssist. It includes website name, push ID, allowed domains, URL format string, and web service URL. ```json { "websiteName": "onesignal", "websitePushID": "web.com.pushassist.push", "allowedDomains": ["https://onesignal.pushassist.com"], "urlFormatString": "https://%@", "webServiceURL": "https://pushassist.com/api" } ``` -------------------------------- ### Set Debug Log Level Source: https://github.com/onesignal/onesignal-website-sdk/blob/main/MIGRATION_GUIDE.md Turns on logging with the specified log level. Available levels include 'trace', 'debug', 'info', 'warn', and 'error'. ```javascript OneSignal.Debug.setLogLevel("trace"); ``` -------------------------------- ### Observe Layout Shift Events Source: https://github.com/onesignal/onesignal-website-sdk/blob/main/preview/index.html This snippet sets up a PerformanceObserver to detect and log layout shift events. It filters out shifts caused by recent user input. ```javascript addEventListener('load', () => { new PerformanceObserver((list) => { list.getEntries().forEach((entry) => { if (entry.hadRecentInput) return; console.info('layout-shift detected', { entry }); }); }).observe({ type: 'layout-shift', buffered: true }); }); ``` -------------------------------- ### Push Subscription Namespace Source: https://github.com/onesignal/onesignal-website-sdk/blob/main/MIGRATION_GUIDE.md Provides methods to manage user push notification subscriptions, including opting in, opting out, and retrieving subscription status and tokens. ```APIDOC ## Push Subscription Namespace ### Description Manages user push notification subscriptions. ### Methods #### `id` Gets the current user's ID. #### `token` Gets the current user's push notification token. #### `optedIn` Gets a boolean value indicating whether the current user is subscribed to push notifications. #### `optIn()` Subscribes the current user to push notifications. **Asynchronous:** Yes #### `optOut()` Unsubscribes the current user from push notifications. **Asynchronous:** Yes #### `addEventListener(event, listener)` Adds an event listener for the `change` event. **Parameters:** - `event` (string) - Must be "change". - `listener` ((change: SubscriptionChangeEvent) => void) - The callback function to execute when the event fires. **Synchronous:** Yes #### `removeEventListener(event, listener)` Removes an event listener for the `change` event. **Parameters:** - `event` (string) - Must be "change". - `listener` ((change: SubscriptionChangeEvent) => void) - The callback function to remove. **Synchronous:** Yes ``` -------------------------------- ### Initialize OneSignal SDK with App ID and Safari Web ID Source: https://github.com/onesignal/onesignal-website-sdk/blob/main/index.html Initializes the OneSignal SDK with your application ID and Safari web ID. It also configures the notification button to be enabled and to show a badge after 0 interactions. Use this snippet to set up OneSignal for web push notifications. ```javascript const appId = new URLSearchParams(window.location.search).get('app_id') || '%VITE_APP_ID%'; window.OneSignalDeferred = window.OneSignalDeferred || []; OneSignalDeferred.push(async function (OneSignal) { OneSignal.Debug.setLogLevel('trace'); OneSignal._isNewVisitor = true; OneSignal.init({ appId, safari_web_id: 'web.onesignal.auto.6187ce57-f346-4a86-93e4-7d70d494c000', notifyButton: { enable: true, prenotify: true, showBadgeAfter: 0, }, }); }); ``` -------------------------------- ### Include OneSignal SDK in HTML Source: https://github.com/onesignal/onesignal-website-sdk/wiki/Self-Hosting-the-JavaScript-Web-SDK Replace the CDN URL with your self-hosted SDK file when including the OneSignal SDK in your HTML pages. ```html ``` -------------------------------- ### Update OneSignal Initialization with Deferred Push Source: https://github.com/onesignal/onesignal-website-sdk/blob/main/MIGRATION_GUIDE.md Migrates the OneSignal initialization process from the older `OneSignal.push` to the new `OneSignalDeferred.push` method, allowing for asynchronous initialization with the OneSignal object passed as an argument. ```javascript window.OneSignalDeferred = window.OneSignalDeferred || []; OneSignalDeferred.push(async function (OneSignal) { await OneSignal.init({}); }); ``` -------------------------------- ### Check Safari Icon DPI with ImageMagick Source: https://github.com/onesignal/onesignal-website-sdk/wiki/Safari-Registration-Bug Use this command to verify the dimensions and DPI of your Safari icon file. Ensure it meets the required 72x72 DPI. ```bash identify -format "%w x %h %x x %y" PATH_TO_FILE ``` -------------------------------- ### Fake Specific Timers with Vitest Source: https://github.com/onesignal/onesignal-website-sdk/blob/main/TESTS.md When touching IndexedDB, avoid using vi.useFakeTimers() without restrictions. Instead, fake only the specific timer APIs needed. ```typescript // Only fake setInterval vi.useFakeTimers({ toFake: ['setInterval'] }); // Only fake Date vi.useFakeTimers({ toFake: ['Date'] }); // Only fake setTimeout/clearTimeout vi.useFakeTimers({ toFake: ['setTimeout', 'clearTimeout'] }); ``` -------------------------------- ### Update Service Worker Configuration in init Source: https://github.com/onesignal/onesignal-website-sdk/blob/main/MIGRATION_GUIDE.md Shows how to configure custom service worker parameters like scope and path directly within the `OneSignal.init` call, replacing the older global parameter assignments. ```javascript await OneSignal.init({ // ... keep other pre-existing params, such as appId serviceWorkerParam: { scope: '/myCustomScope' }, serviceWorkerPath: '/myPath/OneSignalSDKWorker.js', }); ``` -------------------------------- ### OneSignal Safari Push Package Configuration Source: https://github.com/onesignal/onesignal-website-sdk/wiki/What-happens-if-...? This JSON object represents the configuration for a Safari push package provided by OneSignal. It includes website name, push ID, allowed domains, URL format string, and web service URL. ```json { "websiteName": "OneSignal Test WordPress Blog", "websitePushID": "web.onesignal.auto.115f8fcb-d4e8-44f7-85e0-0f5ff0e5093f", "allowedDomains": ["http://notify.tech", "http://www.notify.tech", "https://notify.tech", "https://www.notify.tech"], "urlFormatString": "https://onesignal.com/sdks/safariNotificationOpened?params=%@", "webServiceURL": "https://onesignal.com/api/v1/safari" } ``` -------------------------------- ### Show Email Slidedown Prompt Source: https://github.com/onesignal/onesignal-website-sdk/blob/main/preview/index.html Displays a slidedown prompt for email subscriptions using the OneSignal SDK. ```javascript function showEmailSlidedown() { OneSignalDeferred.push(function (onesignal) { onesignal.Slidedown.promptEmail(); }); } ``` -------------------------------- ### Mock Fetch Response with nock Source: https://github.com/onesignal/onesignal-website-sdk/blob/main/TESTS.md Use the custom nock helper to mock a response for a fetch call. This method is not recommended for general use. ```typescript import { nock } from '__test__/support/mocks/nock'; nock({}, 400); await someFetchCall(); ``` -------------------------------- ### Notifications Namespace Source: https://github.com/onesignal/onesignal-website-sdk/blob/main/MIGRATION_GUIDE.md Provides methods for managing push notifications, including requesting permissions, setting default notification properties, and listening to notification events. ```APIDOC ## Notifications Namespace ### Description Provides methods for managing push notifications, including requesting permissions, setting default notification properties, and listening to notification events. ### Methods #### `setDefaultUrl(url: string)` - **Description**: Sets the default URL for notifications. - **Sync/Async**: `async` #### `setDefaultTitle(title: string)` - **Description**: Sets the default title for notifications. - **Sync/Async**: `async` #### `isPushSupported()` - **Description**: Returns true if the current browser supports web push. - **Sync/Async**: `sync` #### `requestPermission()` - **Description**: Requests push notifications permission via the native browser prompt. - **Sync/Async**: `async` #### `permission` - **Description**: Returns true if your site has permission to display notifications. - **Sync/Async**: (Not specified) #### `permissionNative` - **Description**: Returns browser's native notification permission status; available statuses are `"default"`, `"granted"`, or `"denied"`. - **Sync/Async**: (Not specified) #### `addEventListener(event: string, listener: (arg: any) => {})` - **Description**: Adds an event listener for notification-related events such as `click`, `foregroundWillDisplay`, `dismiss`, `permissionPromptDisplay`, and `permissionChange`. - **Sync/Async**: `sync` #### `removeEventListener(listener: () => {})` - **Description**: Removes an event listener. - **Sync/Async**: `sync` ``` -------------------------------- ### WindowClient Interface Source: https://github.com/onesignal/onesignal-website-sdk/wiki/Future-Notification-Clicked-Spec Represents a browser tab or window that can receive events. Includes properties like focus state, visibility, ID, and URL. ```javascript interface WindowClient { focused: Boolean, visibilityState: String, id: UUID, url: String } ``` -------------------------------- ### Listen for OneSignal Permission Prompt Display Event Source: https://github.com/onesignal/onesignal-website-sdk/blob/main/preview/index.html Adds a listener for the 'permissionPromptDisplay' event, which is triggered when the OneSignal permission prompt is shown to the user. This allows for custom actions before or during prompt display. ```javascript OneSignalDeferred.push(function (onesignal) { onesignal.Notifications.addEventListener('permissionPromptDisplay', function (event) { showEventAlert('permissionPromptDisplay', { event }); }); }); ``` -------------------------------- ### Show SMS and Email Slidedown Prompt Source: https://github.com/onesignal/onesignal-website-sdk/blob/main/preview/index.html Displays a slidedown prompt for both SMS and email subscriptions using the OneSignal SDK. ```javascript function showSmsAndEmailSlidedown() { OneSignalDeferred.push(function (onesignal) { onesignal.Slidedown.promptSmsAndEmail(); }); } ``` -------------------------------- ### OneSignal Initialization and App ID Resolution Source: https://github.com/onesignal/onesignal-website-sdk/blob/main/preview/pageA.html Initializes OneSignal, robustly resolving the app_id from query parameters or local storage, with a default fallback. This snippet is used on Page A to ensure proper initialization even when navigating between pages or in PWA contexts. ```javascript console.log('!!!! [SDK-4336 PAGE A] OneSignal initialize'); function getUrlQueryParam(name) { const urlParams = new URLSearchParams(window.location.search); return urlParams.get(name); } // Resolve the app_id robustly. The in-page links to Page B/Page A don't // carry the query string, and on an iOS standalone (home-screen) PWA the // localStorage fallback isn't reliable across A->B->A navigations because // storage is partitioned per context. Without a hardcoded fallback, the // B->A load calls OneSignal.init with appId=null -> InvalidAppIdError. const DEFAULT_APP_ID = 'b79087eb-8531-4d2d-a6f5-726f797891c7'; let appId = getUrlQueryParam('app_id'); try { if (appId) localStorage.setItem('sdk4336_app_id', appId); else appId = localStorage.getItem('sdk4336_app_id'); } catch (e) {} appId = appId || DEFAULT_APP_ID; const SERVICE_WORKER_PATH = 'push/onesignal/'; var OneSignalDeferred = window.OneSignalDeferred || []; OneSignalDeferred.push(async function (OneSignal) { const t0 = performance.now(); await OneSignal.init({ appId, serviceWorkerParam: { scope: '/' + SERVICE_WORKER_PATH }, serviceWorkerPath: SERVICE_WORKER_PATH + 'OneSignalSDKWorker.js', }); const elapsed = Math.round(performance.now() - t0); console.log(`!!!! [SDK-4336 PAGE A] OneSignal initialized (${elapsed}ms)`); }); ``` -------------------------------- ### User.addEventListener Source: https://github.com/onesignal/onesignal-website-sdk/blob/main/MIGRATION_GUIDE.md Adds an event listener for the 'change' event on the user. This function is synchronous. ```APIDOC ## User.addEventListener ### Description Adds an event listener for the `change` event. ### Method Synchronous JavaScript function call. ### Function Signature `OneSignal.User.addEventListener(event: "change", listener: (change: UserChangeEvent) => void)` ### Parameters #### Arguments - **event** (string) - Required - Must be the string "change". - **listener** (function) - Required - The callback function to execute when the user data changes. It receives a `UserChangeEvent` object. ``` -------------------------------- ### Listen for OneSignal Notification Dismiss Event Source: https://github.com/onesignal/onesignal-website-sdk/blob/main/preview/index.html Sets up a listener for the 'dismiss' event, which occurs when a notification is dismissed by the user. This can be used for analytics or follow-up actions. ```javascript OneSignalDeferred.push(function (onesignal) { onesignal.Notifications.addEventListener('dismiss', function (event) { showEventAlert('dismiss', { event }); }); }); ``` -------------------------------- ### Show SMS Slidedown Prompt Source: https://github.com/onesignal/onesignal-website-sdk/blob/main/preview/index.html Displays a slidedown prompt for SMS subscriptions using the OneSignal SDK. ```javascript function showSmsSlidedown() { OneSignalDeferred.push(function (onesignal) { onesignal.Slidedown.promptSms(); }); } ``` -------------------------------- ### Debug Namespace Source: https://github.com/onesignal/onesignal-website-sdk/blob/main/MIGRATION_GUIDE.md Provides methods for controlling the SDK's logging level for debugging purposes. ```APIDOC ## Debug Namespace ### Description Controls the SDK's logging level for debugging. ### Methods #### `setLogLevel(logLevel)` Turns on logging with the given log level. **Parameters:** - `logLevel` (string) - The desired log level. Accepted values are: "trace", "debug", "info", "warn", "error". **Synchronous:** Yes ``` -------------------------------- ### Show Category Slidedown Prompt Source: https://github.com/onesignal/onesignal-website-sdk/blob/main/preview/index.html Displays a slidedown prompt for push notification categories using the OneSignal SDK. ```javascript function showCategorySlidedown() { OneSignalDeferred.push(function (onesignal) { onesignal.Slidedown.promptPushCategories(); }); } ``` -------------------------------- ### User.addTags Source: https://github.com/onesignal/onesignal-website-sdk/blob/main/MIGRATION_GUIDE.md Adds multiple tags for the current user. This function is synchronous. ```APIDOC ## User.addTags ### Description Adds multiple tags for the current user. ### Method Synchronous JavaScript function call. ### Function Signature `OneSignal.User.addTags(tags: { [key: string]: string })` ### Parameters #### Arguments - **tags** (object) - Required - An object where keys are tag keys and values are tag values. ``` -------------------------------- ### JavaScript Logging and Permission Check Source: https://github.com/onesignal/onesignal-website-sdk/blob/main/index.html This snippet provides utility functions for logging messages with timestamps and checking/requesting push notification permissions. It handles both legacy Safari push and standard VAPID push, updating the UI to reflect the current status. ```javascript const $ = (id) => document.getElementById(id); const log = (msg, cls = '') => { const el = $('log'); const span = document.createElement('span'); if (cls) span.className = cls; span.textContent = `\[${new Date().toLocaleTimeString()}\] ${msg}\n `; el.appendChild(span); el.scrollTop = el.scrollHeight; }; function refreshInfo() { $('ua').textContent = navigator.userAgent; const hasSafari = typeof window.safari !== 'undefined' && typeof window.safari.pushNotification !== 'undefined'; $('safari-exists').textContent = hasSafari ? 'Yes' : 'No'; if (hasSafari) { try { const safariWebId = OneSignal?.config?.safariWebId || 'web.onesignal.auto.6187ce57-f346-4a86-93e4-7d70d494c000'; const perm = window.safari.pushNotification.permission(safariWebId); $('legacy-perm').textContent = perm.permission; $('legacy-token').textContent = perm.deviceToken || '(null)'; if (perm.permission === 'granted' && perm.deviceToken) { $('push-path').innerHTML = 'Legacy Safari Push (existing subscriber)'; } else { $('push-path').innerHTML = 'Standard VAPID Push (new user)'; } } catch (e) { $('legacy-perm').textContent = 'Error: ' + e.message; $('legacy-token').textContent = '—'; } } else { $('legacy-perm').textContent = 'N/A (not Safari)'; $('legacy-token').textContent = 'N/A'; const isVapid = typeof PushSubscriptionOptions !== 'undefined'; $('push-path').innerHTML = isVapid ? 'Standard VAPID Push' : 'Push not supported'; } const vapidSupport = typeof PushSubscriptionOptions !== 'undefined'; $('vapid-support').textContent = vapidSupport ? 'Supported' : 'Not available'; $('notif-perm').textContent = typeof Notification !== 'undefined' ? Notification.permission : 'N/A'; } $('request-perm').addEventListener('click', async () => { log('Requesting push permission...', 'info'); try { await OneSignal.Notifications.requestPermission(); log('Permission granted!', 'success'); } catch (e) { log('Error: ' + e.message, 'error'); } refreshInfo(); }); $('refresh-info').addEventListener('click', refreshInfo); window.OneSignalDeferred = window.OneSignalDeferred || []; OneSignalDeferred.push(() => { log('OneSignal initialized', 'success'); refreshInfo(); }); // Initial info on page load setTimeout(refreshInfo, 500); ``` -------------------------------- ### Listen for OneSignal Slidedown Shown Event Source: https://github.com/onesignal/onesignal-website-sdk/blob/main/preview/index.html Adds an event listener for 'slidedownShown', which fires when the OneSignal slidedown prompt is displayed. This can be used to track prompt visibility or trigger subsequent actions. ```javascript OneSignalDeferred.push(function (onesignal) { onesignal.Slidedown.addEventListener('slidedownShown', function (event) { showEventAlert('slidedownShown', { event }); }); }); ``` -------------------------------- ### Opt-in to Push Notifications Source: https://github.com/onesignal/onesignal-website-sdk/blob/main/MIGRATION_GUIDE.md Subscribes the current user to push notifications. This function should be called after SDK initialization. ```javascript OneSignal.User.PushSubscription.optIn(); ``` -------------------------------- ### Hide Subscription Bell or Launcher Source: https://github.com/onesignal/onesignal-website-sdk/wiki/Legacy-Supported-Properties Hides the subscription bell or the notification launcher if they exist. Use this when you need to programmatically control the visibility of these UI elements. ```javascript if (OneSignal.subscriptionBell && OneSignal.subscriptionBell.hide) { OneSignal.subscriptionBell.hide(); } else if (OneSignal.notifyButton && OneSignal.notifyButton.launcher) { OneSignal.notifyButton.launcher.hide(); } ``` -------------------------------- ### Check Push Notification Support Source: https://github.com/onesignal/onesignal-website-sdk/blob/main/MIGRATION_GUIDE.md Synchronously checks if the current browser supports web push notifications. ```javascript OneSignal.isPushSupported(); ``` -------------------------------- ### OneSignal.on/once('notificationPendingClick', callback) Source: https://github.com/onesignal/onesignal-website-sdk/wiki/Future-Notification-Clicked-Spec Fires when a notification is clicked but before the default action occurs. This event is broadcast to all open site tabs and allows them to intercept or modify the outcome. ```APIDOC ## OneSignal.on/once('notificationPendingClick', callback) ### Description Occurs when a notification has just been clicked, but before the notification clicked action takes place. This event fires on all open site tabs, and the event specifies the default action to take place (e.g. open a new window, or focus tab #3), and allows each open tab to intercept and modify the final outcome. ### Method `OneSignal.on` or `OneSignal.once` ### Parameters #### Event Name - **notificationPendingClick** (string) - The name of the event to listen for. #### Callback Function - **callback** (function) - A function that will be executed when the event is triggered. It receives a `NotificationPendingClickEvent` object as an argument. ### Event Payload Structure ```javascript interface NotificationPendingClickEvent { notification: Notification, targets: WindowClient[], shouldFocusWindow: Boolean, urlPendingNavigation: String, shouldOpenNewWindow: Boolean } interface WindowClient { focused: Boolean, visibilityState: String, id: UUID, url: String } ``` ### Example ```javascript OneSignal.on('notificationPendingClick', function(event) { console.log('Notification pending click:', event); // Modify event properties here if needed }); ``` ``` -------------------------------- ### Replace setExternalId with logout Source: https://github.com/onesignal/onesignal-website-sdk/blob/main/MIGRATION_GUIDE.md Demonstrates how to log out a user by calling `OneSignal.logout()`, replacing the previous method of setting `externalId` to an empty string or null. ```javascript OneSignal.logout(); ``` -------------------------------- ### Mock delay function with mockDelay helper Source: https://github.com/onesignal/onesignal-website-sdk/blob/main/TESTS.md Use the mockDelay helper to mock the delay function and make it resolve immediately, avoiding time-based delays in tests. ```typescript import { mockDelay } from '__test__/support/helpers/setup'; // Must be called at the top level of the test file (alongside other vi.mock calls) mockDelay(); ``` -------------------------------- ### PushAssist Safari Push Package POST Request Source: https://github.com/onesignal/onesignal-website-sdk/wiki/What-happens-if-...? This cURL command is used to request the Safari push package details from PushAssist. It requires specific headers and a JSON payload containing subdomain, IP address, and segments. ```shell curl -X POST -H "Accept: application/json" -H "Content-Type: application/json" -H "Cache-Control: no-cache" -H "Postman-Token: 10488b0c-da82-d194-4b06-893bf39e88c4" -d '{ "subdomain": "onesignal", "ipaddress": "50.131.165.48", "segments": "" }' "https://pushassist.com/api/v1/pushPackages/web.com.pushassist.push" ``` -------------------------------- ### Listen for OneSignal Push Subscription Change Event Source: https://github.com/onesignal/onesignal-website-sdk/blob/main/preview/index.html Adds an event listener to detect changes in the user's push subscription status. This is useful for updating UI or triggering actions based on subscription state. ```javascript OneSignalDeferred.push(function (onesignal) { onesignal.User.PushSubscription.addEventListener('change', function (event) { showEventAlert('change', { event }); }); }); ``` -------------------------------- ### User.getTags Source: https://github.com/onesignal/onesignal-website-sdk/blob/main/MIGRATION_GUIDE.md Returns the local tags on the current user. This function is synchronous. ```APIDOC ## User.getTags ### Description Returns the local tags on the current user. ### Method Synchronous JavaScript function call. ### Function Signature `OneSignal.User.getTags()` ### Returns - An object containing the user's tags. ``` -------------------------------- ### Update OneSignal Page Script Import Source: https://github.com/onesignal/onesignal-website-sdk/blob/main/MIGRATION_GUIDE.md Replaces the old OneSignal SDK script import with the new v16 page-specific script for improved performance and features. ```html ``` -------------------------------- ### User.addTag Source: https://github.com/onesignal/onesignal-website-sdk/blob/main/MIGRATION_GUIDE.md Adds a tag for the current user. This function is synchronous. ```APIDOC ## User.addTag ### Description Adds a tag for the current user. ### Method Synchronous JavaScript function call. ### Function Signature `OneSignal.User.addTag(key: string, value: string)` ### Parameters #### Arguments - **key** (string) - Required - The key of the tag. - **value** (string) - Required - The value of the tag. ``` -------------------------------- ### OneSignal Safari Push Package POST Request Source: https://github.com/onesignal/onesignal-website-sdk/wiki/What-happens-if-...? This cURL command is used to request the Safari push package details from OneSignal. It requires specific headers and a JSON payload containing the application ID. ```shell curl -X POST -H "Accept: application/json" -H "Content-Type: application/json" -H "Cache-Control: no-cache" -H "Postman-Token: a171c2fd-ef31-136f-1f26-8b5fcd04ba4e" -d '{ "app_id": "c9c4a506-8351-11e5-8d7d-a0369f2d9328" }' "https://onesignal.com/api/v1/safari/v1/pushPackages/web.onesignal.auto.115f8fcb-d4e8-44f7-85e0-0f5ff0e5093f" ``` -------------------------------- ### Request Notification Permission Source: https://github.com/onesignal/onesignal-website-sdk/blob/main/MIGRATION_GUIDE.md Use this snippet to request permission for push notifications from the user's browser. ```javascript await OneSignal.Notifications.requestPermission(); ``` -------------------------------- ### User.addEmail Source: https://github.com/onesignal/onesignal-website-sdk/blob/main/MIGRATION_GUIDE.md Adds an email address for the current user. This function is synchronous. ```APIDOC ## User.addEmail ### Description Adds an email address for the current user. ### Method Synchronous JavaScript function call. ### Function Signature `OneSignal.User.addEmail(email: string)` ### Parameters #### Arguments - **email** (string) - Required - The email address to add. ``` -------------------------------- ### Listen for OneSignal Permission Change Event Source: https://github.com/onesignal/onesignal-website-sdk/blob/main/preview/index.html Registers a listener for the 'permissionChange' event, which fires when the notification permission status changes. It provides the new subscription status. ```javascript OneSignalDeferred.push(function (onesignal) { onesignal.Notifications.addEventListener('permissionChange', function (isSubscribed) { showEventAlert('permissionChange', { isSubscribed }); }); }); ``` -------------------------------- ### Update OneSignal Worker Script Import Source: https://github.com/onesignal/onesignal-website-sdk/wiki/Self-Hosting-the-JavaScript-Web-SDK Modify the `importScripts` path in `OneSignalSDKWorker.js` to point to your self-hosted SDK file. This ensures the worker script loads the correct SDK version. ```javascript importScripts('https://yoursite.com/assets/OneSignalSDK.js'); ``` -------------------------------- ### User.addAliases Source: https://github.com/onesignal/onesignal-website-sdk/blob/main/MIGRATION_GUIDE.md Adds multiple aliases for the current user. This function is synchronous. ```APIDOC ## User.addAliases ### Description Adds multiple aliases for the current user. ### Method Synchronous JavaScript function call. ### Function Signature `OneSignal.User.addAliases(aliases: { [key: string]: string })` ### Parameters #### Arguments - **aliases** (object) - Required - An object where keys are alias labels and values are alias IDs. ``` -------------------------------- ### Set Default Notification URL Source: https://github.com/onesignal/onesignal-website-sdk/blob/main/MIGRATION_GUIDE.md Sets the default URL that will be opened when a notification is clicked. This is an asynchronous operation. ```javascript await OneSignal.setDefaultUrl(url); ``` -------------------------------- ### OneSignal.on/once('notificationClick', callback) Source: https://github.com/onesignal/onesignal-website-sdk/wiki/Future-Notification-Clicked-Spec Fires after the `notificationPendingClick` event and after the notification's click action has been processed. This event is only received by the tab that is the target of the notification click action. ```APIDOC ## OneSignal.on/once('notificationClick', callback) ### Description Occurs after event `notificationPendingClick`, after the notification clicked action takes place. Only the tab that is the target of the notification clicked action will receive this event. ### Method `OneSignal.on` or `OneSignal.once` ### Parameters #### Event Name - **notificationClick** (string) - The name of the event to listen for. #### Callback Function - **callback** (function) - A function that will be executed when the event is triggered. It receives a `NotificationClickEvent` object as an argument. ### Event Payload Structure ```javascript interface NotificationClickEvent { notification: Notification } ``` ### Example ```javascript OneSignal.on('notificationClick', function(event) { console.log('Notification clicked:', event); }); ``` ``` -------------------------------- ### Add Notification Event Listener Source: https://github.com/onesignal/onesignal-website-sdk/blob/main/MIGRATION_GUIDE.md Adds an event listener for various notification-related events such as click, foreground display, and permission changes. The listener callback receives an argument depending on the event type. ```javascript OneSignal.addEventListener(event, listener); ``` -------------------------------- ### Assert on delay spy Source: https://github.com/onesignal/onesignal-website-sdk/blob/main/TESTS.md After using mockDelay, you can assert on the delay spy to verify the correct delay duration was requested. ```typescript import { delay as delaySpy } from 'src/shared/helpers/general'; expect(delaySpy).toHaveBeenCalledWith(30000); ``` -------------------------------- ### NotificationPendingClickEvent Interface Source: https://github.com/onesignal/onesignal-website-sdk/wiki/Future-Notification-Clicked-Spec Details of the event triggered when a notification is clicked, before the default action. Includes the notification object, potential targets, and navigation flags. ```javascript interface NotificationPendingClickEvent { notification: Notification, targets: WindowClient[], shouldFocusWindow: Boolean, urlPendingNavigation: String, shouldOpenNewWindow: Boolean } ``` -------------------------------- ### Add User Alias Source: https://github.com/onesignal/onesignal-website-sdk/blob/main/MIGRATION_GUIDE.md Adds a new alias for the current user. This function is synchronous. ```javascript OneSignal.User.addAlias('my_alias', '1234'); ``` -------------------------------- ### Listen for OneSignal User Change Event Source: https://github.com/onesignal/onesignal-website-sdk/blob/main/preview/index.html Attaches an event listener to monitor changes in user properties or status within the OneSignal SDK. This can be used to react to updates in user data. ```javascript OneSignalDeferred.push(function (onesignal) { onesignal.User.addEventListener('change', function (event) { showEventAlert('change', { event }); }); }); ``` -------------------------------- ### Listen for Notification Click Event Source: https://github.com/onesignal/onesignal-website-sdk/wiki/Future-Notification-Clicked-Spec This event fires after the default notification click action has completed. It is only received by the tab targeted by the notification. ```javascript OneSignal.on('notificationClick', callback) ``` -------------------------------- ### Send Outcome with Weight to OneSignal Source: https://github.com/onesignal/onesignal-website-sdk/blob/main/preview/index.html Sends an outcome event to OneSignal with an associated weight. This allows for more granular tracking of actions, potentially for A/B testing or weighted conversions. ```javascript function sendOutcomeWithWeight() { OneSignalDeferred.push(function (onesignal) { const outcomeName = document.querySelector('#outcome_name').value; const outcomeWeight = parseFloat(document.querySelector('#outcome_weight').value); onesignal.Session.sendOutcome(outcomeName ``` -------------------------------- ### Replace setExternalId with login Source: https://github.com/onesignal/onesignal-website-sdk/blob/main/MIGRATION_GUIDE.md Updates the method for identifying users from `setExternalId` to the new `login` method, which is part of the user-centered model. ```javascript OneSignal.login('myId'); ``` -------------------------------- ### Listen for Pending Notification Click Event Source: https://github.com/onesignal/onesignal-website-sdk/wiki/Future-Notification-Clicked-Spec Use this event to intercept notification clicks before the default action occurs. It fires on all open tabs and allows modification of the outcome. ```javascript OneSignal.on('notificationPendingClick', callback) ``` -------------------------------- ### Listen for OneSignal Notification Click Event Source: https://github.com/onesignal/onesignal-website-sdk/blob/main/preview/index.html Registers a listener for the 'click' event, which is triggered when a user clicks on a notification. This is essential for handling user engagement with notifications. ```javascript OneSignalDeferred.push(function (onesignal) { onesignal.Notifications.addEventListener('click', function (event) { showEventAlert('click', { event }); }); }); ``` -------------------------------- ### Add Push Notification Change Event Listener Source: https://github.com/onesignal/onesignal-website-sdk/blob/main/MIGRATION_GUIDE.md Adds an event listener for the 'change' event on the push subscription. The listener function will be called when the subscription status changes. ```javascript OneSignal.User.PushSubscription.addEventListener('change', (change) => { // Handle subscription change }); ``` -------------------------------- ### User.addAlias Source: https://github.com/onesignal/onesignal-website-sdk/blob/main/MIGRATION_GUIDE.md Adds a new alias for the current user. This function is synchronous. ```APIDOC ## User.addAlias ### Description Adds a new alias for the current user. ### Method Synchronous JavaScript function call. ### Function Signature `OneSignal.User.addAlias(label: string, id: string)` ### Parameters #### Arguments - **label** (string) - Required - The label for the alias. - **id** (string) - Required - The ID for the alias. ``` -------------------------------- ### Listen for OneSignal Foreground Notification Display Event Source: https://github.com/onesignal/onesignal-website-sdk/blob/main/preview/index.html Attaches a listener for the 'foregroundWillDisplay' event, which fires just before a notification is displayed to the user while the app is in the foreground. This allows for modification of the notification before display. ```javascript OneSignalDeferred.push(function (onesignal) { onesignal.Notifications.addEventListener('foregroundWillDisplay', function (event) { showEventAlert('foregroundWillDisplay', event); }); }); ``` -------------------------------- ### APS D Log - PushAssist Topic Source: https://github.com/onesignal/onesignal-website-sdk/wiki/What-happens-if-...? This log entry shows a high-priority message received by apsd for the PushAssist topic, indicating a notification is being processed for that provider. ```log Dec 7 16:52:15 COMPUTER-jpang apsd[77]: : Received high priority message for topic 'web.com.pushassist.push' with payload ``` -------------------------------- ### Set Default Notification Title Source: https://github.com/onesignal/onesignal-website-sdk/blob/main/MIGRATION_GUIDE.md Sets the default title for notifications. This is an asynchronous operation. ```javascript await OneSignal.setDefaultTitle(title); ``` -------------------------------- ### Request OneSignal Notification Permission Source: https://github.com/onesignal/onesignal-website-sdk/blob/main/preview/pageA.html Requests the user's permission to send notifications using OneSignal. This function should be called after OneSignal has been initialized. ```javascript async function requestNotificationPermission() { window.OneSignalDeferred = window.OneSignalDeferred || []; OneSignalDeferred.push(async function (OneSignal) { await OneSignal.Notifications.requestPermission(); }); } ``` -------------------------------- ### User.onesignalId Source: https://github.com/onesignal/onesignal-website-sdk/blob/main/MIGRATION_GUIDE.md Returns the local OneSignal ID for the current user. This property is synchronous. ```APIDOC ## User.onesignalId ### Description Returns the local OneSignal ID for the current user. ### Method Synchronous JavaScript property access. ### Returns - The OneSignal ID (string) for the current user. ``` -------------------------------- ### Update OneSignal Service Worker Script Import Source: https://github.com/onesignal/onesignal-website-sdk/blob/main/MIGRATION_GUIDE.md Updates the import statement within the OneSignal Service Worker file to use the new v16 service worker script. ```javascript importScripts('https://cdn.onesignal.com/sdks/web/v16/OneSignalSDK.sw.js'); ``` -------------------------------- ### NotificationClickEvent Interface Source: https://github.com/onesignal/onesignal-website-sdk/wiki/Future-Notification-Clicked-Spec Represents the event that occurs after a notification click action has been processed. It contains the notification object. ```javascript interface NotificationClickEvent { notification: Notification } ```