### Complete Subscription Flow
Source: https://github.com/onesignal/onesignal-vue3/blob/main/_autodocs/quick-reference.md
Guides through the process of initializing OneSignal, checking push support, and requesting notification permissions.
```typescript
async function setupNotifications() {
try {
// Check support
if (!this.$OneSignal.Notifications.isPushSupported()) {
console.warn('Push not supported')
return
}
// Initialize
await this.$OneSignal.init({
appId: 'xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx'
})
// Request permission
const granted = await this.$OneSignal.Notifications.requestPermission()
if (granted) {
console.log('User subscribed!')
}
} catch (error) {
console.error('Setup failed:', error)
}
}
```
--------------------------------
### Install and Initialize OneSignal Vue3 SDK
Source: https://github.com/onesignal/onesignal-vue3/blob/main/_autodocs/quick-reference.md
Import and use the OneSignalVuePlugin. Initialization can be done globally with options or manually later in a component.
```typescript
import OneSignalVuePlugin from '@onesignal/onesignal-vue3'
// Option 1: With initialization
createApp(App)
.use(OneSignalVuePlugin, {
appId: 'xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx'
})
.mount('#app')
// Option 2: Manual initialization
createApp(App)
.use(OneSignalVuePlugin)
.mount('#app')
// Later in component:
await this.$OneSignal.init({
appId: 'xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx'
})
```
--------------------------------
### Complex OneSignal Vue3 Setup
Source: https://github.com/onesignal/onesignal-vue3/blob/main/_autodocs/api-reference/debug-and-composable.md
Demonstrates a complex setup for the OneSignal Vue3 plugin, including listening for notification clicks, user tracking with email and tags, and managing push subscription changes. It also includes cleanup for event listeners.
```typescript
import { useOneSignal } from '@onesignal/onesignal-vue3'
import { ref, onBeforeUnmount } from 'vue'
export default {
setup() {
const OneSignal = useOneSignal()
const userEmail = ref('')
const isNotificationsEnabled = ref(false)
// Listen to notifications
const handleNotificationClick = (event) => {
console.log('Notification clicked:', event.notification)
navigateTo(event.result.url)
}
OneSignal.Notifications.addEventListener('click', handleNotificationClick)
// Track user
const loginUser = (userId, email) => {
OneSignal.login(userId)
OneSignal.User.addEmail(email)
OneSignal.User.addTag('email', email)
}
// Listen for subscription changes
const handleSubscriptionChange = (event) => {
isNotificationsEnabled.value = event.current.optedIn
}
OneSignal.User.PushSubscription.addEventListener(
'change',
handleSubscriptionChange
)
// Cleanup listeners
onBeforeUnmount(() => {
OneSignal.Notifications.removeEventListener(
'click',
handleNotificationClick
)
OneSignal.User.PushSubscription.removeEventListener(
'change',
handleSubscriptionChange
)
})
return {
userEmail,
isNotificationsEnabled,
loginUser
}
}
}
```
--------------------------------
### Vue Plugin Installation
Source: https://github.com/onesignal/onesignal-vue3/blob/main/_autodocs/module-structure.md
Installs the OneSignal plugin by registering the `$OneSignal` global property and calling the `init()` method with provided configuration. This enables TypeScript support for `$OneSignal` via module augmentation.
```typescript
const OneSignalVuePlugin = {
install(app: App, options: IInitObject) {
app.config.globalProperties.$OneSignal = OneSignalNamespace
app.config.globalProperties.$OneSignal.init(options)
}
}
```
--------------------------------
### Initialize OneSignal with Prompt Configuration
Source: https://github.com/onesignal/onesignal-vue3/blob/main/_autodocs/api-reference/init.md
Configure subscription prompts during OneSignal initialization. This example sets up a slidedown prompt with custom text and delay settings.
```typescript
await this.$OneSignal.init({
appId: 'xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx',
promptOptions: {
slidedown: {
prompts: [
{
type: 'push',
autoPrompt: true,
text: {
actionMessage: 'Get updates from our app',
acceptButton: 'Subscribe',
cancelButton: 'Not now'
},
delay: {
pageViews: 1,
timeDelay: 5
}
}
]
}
}
})
```
--------------------------------
### Install OneSignal Vue3 with npm
Source: https://github.com/onesignal/onesignal-vue3/blob/main/README.md
Install the OneSignal Vue3 plugin using npm. This command adds the package to your project dependencies.
```bash
npm install --save @onesignal/onesignal-vue3
```
--------------------------------
### Install OneSignal Vue3 with Yarn
Source: https://github.com/onesignal/onesignal-vue3/blob/main/README.md
Install the OneSignal Vue3 plugin using Yarn. This command adds the package to your project dependencies.
```bash
yarn add @onesignal/onesignal-vue3
```
--------------------------------
### Complete OneSignal Vue3 Initialization with Customizations
Source: https://github.com/onesignal/onesignal-vue3/blob/main/_autodocs/configuration.md
Shows a comprehensive example of initializing OneSignal Vue3 with various options, including auto-registration, privacy consent, service worker path, prompt settings, welcome notifications, button customization, and webhook configuration.
```typescript
await this.$OneSignal.init({
appId: 'xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx',
autoRegister: true,
autoResubscribe: true,
requiresUserPrivacyConsent: false,
serviceWorkerPath: '/onesignal/OneSignalSDKWorker.js',
subdomainName: 'myapp',
persistNotification: true,
notificationClickHandlerMatch: 'origin',
notificationClickHandlerAction: 'navigate',
promptOptions: {
slidedown: {
prompts: [
{
type: 'push',
autoPrompt: true,
delay: {
pageViews: 1,
timeDelay: 10
},
text: {
actionMessage: 'Get exclusive updates',
acceptButton: 'Subscribe',
cancelButton: 'Not now'
}
}
]
}
},
welcomeNotification: {
title: 'Welcome!',
message: 'Thanks for subscribing',
url: 'https://example.com/welcome'
},
notifyButton: {
enable: true,
position: 'bottom-right',
size: 'medium',
prenotify: true,
showCredit: false,
text: {
'dialog.main.title': 'Notifications',
'dialog.main.button.subscribe': 'Enable',
'dialog.main.button.unsubscribe': 'Disable',
'message.prenotify': 'You have 1 unread message',
'tip.state.subscribed': 'You\'re subscribed'
}
},
webhooks: {
cors: true,
'notification.clicked': 'https://api.example.com/webhooks/notification/clicked',
'notification.willDisplay': 'https://api.example.com/webhooks/notification/display'
}
})
```
--------------------------------
### Plugin Setup with Initialization Options
Source: https://github.com/onesignal/onesignal-vue3/blob/main/README.md
Set up the OneSignal Vue3 plugin by passing initialization options directly to the `use` function in your main Vue application file. Ensure your appId is correctly provided.
```js
import { createApp } from 'vue';
import OneSignalVuePlugin from '@onesignal/onesignal-vue3';
createApp(App)
.use(OneSignalVuePlugin, {
appId: 'xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx',
})
.mount('#app');
```
--------------------------------
### Deferred Loading Mechanism Example
Source: https://github.com/onesignal/onesignal-vue3/blob/main/_autodocs/module-structure.md
Queues a callback function to execute with the loaded SDK instance when it becomes available. This is used for handling asynchronous script loading.
```typescript
window.OneSignalDeferred?.push((OneSignal) => {
OneSignal.User.addTag(key, value)
})
```
--------------------------------
### Set and Get Language
Source: https://github.com/onesignal/onesignal-vue3/blob/main/_autodocs/quick-reference.md
Set the user's preferred language and retrieve the current language setting.
```typescript
this.$OneSignal.User.setLanguage('en')
this.$OneSignal.User.setLanguage('es')
```
```typescript
const lang = await this.$OneSignal.User.getLanguage()
```
--------------------------------
### Opt-in/Out Push Subscription with Composition API
Source: https://github.com/onesignal/onesignal-vue3/blob/main/_autodocs/api-reference/debug-and-composable.md
Integrates the OneSignal SDK into a Vue 3 component using the Composition API's `setup` function. This example shows how to manage push notification subscription status.
```typescript
import { useOneSignal } from '@onesignal/onesignal-vue3'
import { ref } from 'vue'
export default {
setup() {
const OneSignal = useOneSignal()
const isOptedIn = ref(false)
const handleToggleNotifications = async () => {
if (isOptedIn.value) {
await OneSignal.User.PushSubscription.optOut()
} else {
await OneSignal.User.PushSubscription.optIn()
}
}
return { handleToggleNotifications, isOptedIn }
}
}
```
--------------------------------
### Handle User Login Action
Source: https://github.com/onesignal/onesignal-vue3/blob/main/_autodocs/api-reference/authentication.md
Example of handling a user login action, including error handling for the OneSignal login process. This method must be called after init().
```typescript
async function handleLogin(userId: string) {
try {
await this.$OneSignal.login(userId)
console.log('User logged in to OneSignal')
} catch (error) {
console.error('Login failed:', error)
}
}
```
--------------------------------
### Plugin Setup without Initial Options
Source: https://github.com/onesignal/onesignal-vue3/blob/main/README.md
Set up the OneSignal Vue3 plugin without initial options, allowing for separate initialization within a component. The plugin exposes a global $OneSignal property.
```js
//main
import { createApp } from 'vue';
import OneSignalVuePlugin from '@onesignal/onesignal-vue3';
createApp(App).use(OneSignalVuePlugin).mount('#app');
// component
this.$OneSignal.init({
appId: 'xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx',
});
```
--------------------------------
### Complete OneSignal Initialization with Error Handling
Source: https://github.com/onesignal/onesignal-vue3/blob/main/_autodocs/errors.md
Initializes the OneSignal SDK, handling various potential errors like unsupported browsers, invalid app IDs, or script loading failures. Use this for robust SDK setup.
```typescript
async function initializeOneSignal() {
try {
// Check browser support first
if (!this.$OneSignal.Notifications.isPushSupported()) {
console.warn('Push notifications not supported')
return false
}
// Initialize SDK
await this.$OneSignal.init({
appId: 'xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx'
})
// Initialize user if logged in
if (this.userId) {
await this.$OneSignal.login(this.userId)
}
return true
} catch (error) {
if (error.message.includes('already initialized')) {
console.warn('OneSignal already initialized')
return true // Not a critical error
} else if (error.message.includes('appId')) {
console.error('Invalid OneSignal configuration')
return false
} else if (error.message.includes('script failed')) {
console.error('Failed to load OneSignal SDK, retrying...')
// Could implement retry logic here
return false
} else {
console.error('OneSignal initialization error:', error)
return false
}
}
}
```
--------------------------------
### Prompt Push Notifications on Button Click
Source: https://github.com/onesignal/onesignal-vue3/blob/main/_autodocs/api-reference/slidedown.md
An example of how to trigger the push notification prompt when a user interacts with a button. Ensure the function is called within an appropriate event handler.
```typescript
// Prompt on button click
async function askForNotifications() {
await this.$OneSignal.Slidedown.promptPush()
}
```
--------------------------------
### IInitObject
Source: https://github.com/onesignal/onesignal-vue3/blob/main/_autodocs/types.md
Configuration options for the `init()` method, specifying application ID, registration behavior, prompt settings, welcome notifications, and more.
```APIDOC
## IInitObject
### Description
Configuration options for `init()`.
### Fields
- **appId** (string) - Yes - OneSignal Application ID
- **autoRegister** (boolean) - No - Auto-register users
- **autoResubscribe** (boolean) - No - Auto-resubscribe users
- **path** (string) - No - SDK path
- **serviceWorkerPath** (string) - No - Path to the service worker file
- **serviceWorkerUpdaterPath** (string) - No - Path to the service worker updater file
- **subdomainName** (string) - No - Subdomain name
- **allowLocalhostAsSecureOrigin** (boolean) - No - Allow localhost as a secure origin
- **requiresUserPrivacyConsent** (boolean) - No - Require user privacy consent
- **persistNotification** (boolean) - No - Persist notification
- **notificationClickHandlerMatch** (string) - No - Match type for notification click handler ('exact' or 'origin')
- **notificationClickHandlerAction** (string) - No - Action for notification click handler ('navigate' or 'focus')
- **promptOptions** (object) - No - Configuration for subscription prompts
- **welcomeNotification** (object) - No - Welcome notification settings
- **notifyButton** (object) - No - Subscription bell configuration
- **webhooks** (object) - No - Webhook URLs for notification events
- **serviceWorkerParam** (object) - No - Service worker parameters
- **serviceWorkerOverrideForTypical** (boolean) - No - Override service worker for typical cases
- **scriptSrc** (string) - No - Custom SDK script URL
- **[key: string]** (unknown) - No - Additional properties
**Used by:** `init()`
```
--------------------------------
### useOneSignal Composable
Source: https://github.com/onesignal/onesignal-vue3/blob/main/_autodocs/api-reference/debug-and-composable.md
A Vue 3 composable function that returns the OneSignal SDK instance. Use this in the setup() function or top-level
```
#### Usage with Options API (`this.$OneSignal`)
```vue
```
#### Composition API with setup function
```typescript
import { useOneSignal } from '@onesignal/onesignal-vue3'
import { ref } from 'vue'
export default {
setup() {
const OneSignal = useOneSignal()
const isOptedIn = ref(false)
const handleToggleNotifications = async () => {
if (isOptedIn.value) {
await OneSignal.User.PushSubscription.optOut()
} else {
await OneSignal.User.PushSubscription.optIn()
}
}
return { handleToggleNotifications, isOptedIn }
}
}
```
```
--------------------------------
### Handle OneSignal Init Failure Before Opting In/Out
Source: https://github.com/onesignal/onesignal-vue3/blob/main/_autodocs/errors.md
Shows how to confirm successful SDK initialization before calling `optIn()` or `optOut()` for push subscription management. This avoids errors when the SDK script has failed to load.
```typescript
await this.$OneSignal.User.PushSubscription.optIn()
// Fails if init never succeeded
```
```typescript
async function enableNotifications() {
try {
await this.$OneSignal.init({
appId: 'xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx'
})
await this.$OneSignal.User.PushSubscription.optIn()
} catch (error) {
console.error('Failed to enable notifications:', error)
}
}
```
--------------------------------
### Get Notification Permission Status
Source: https://github.com/onesignal/onesignal-vue3/blob/main/MigrationGuide.md
Retrieves the current permission status for displaying notifications. This is a synchronous operation.
```javascript
const hasPermission = OneSignal.Notifications.permission;
```
--------------------------------
### Configure Welcome Notification
Source: https://github.com/onesignal/onesignal-vue3/blob/main/_autodocs/configuration.md
Set up a welcome notification to be sent to new subscribers. You can customize the title, message, and the URL to open when the notification is clicked. This helps in onboarding new users.
```typescript
welcomeNotification: {
disable?: boolean, // Disable welcome notification
disabled?: boolean, // (Deprecated) Disable welcome notification
title?: string, // Notification title
message: string, // Notification message
url?: string // URL to open
}
```
--------------------------------
### User Alias Structure Example
Source: https://github.com/onesignal/onesignal-vue3/blob/main/MigrationGuide.md
Illustrates the structure for defining aliases, including labels and IDs, for user identification.
```json
{
"aliases": [
{
"label": "external_id",
"id": "1234"
},
{
"label": "my_alias",
"id": "5678"
}
]
}
```
--------------------------------
### Production Initialization with Advanced Options
Source: https://github.com/onesignal/onesignal-vue3/blob/main/_autodocs/configuration.md
Initialize the OneSignal SDK for production with auto-registration, auto-resubscription, and webhook configuration.
```typescript
await this.$OneSignal.init({
appId: 'your-prod-app-id',
autoRegister: true,
autoResubscribe: true,
requiresUserPrivacyConsent: true,
scriptSrc: 'https://my-cdn.example.com/OneSignalSDK.js',
webhooks: {
cors: true,
'notification.clicked': 'https://api.example.com/analytics/notification-clicked'
}
})
// Minimal logging in production
this.$OneSignal.Debug.setLogLevel('warn')
```
--------------------------------
### Initialize OneSignal with Promise (async/await)
Source: https://github.com/onesignal/onesignal-vue3/blob/main/README.md
Initialize the OneSignal plugin using the `init` method within an async function. This method returns a promise that resolves when OneSignal is loaded.
```js
await this.$OneSignal.init({ appId: 'xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx' });
// do other stuff
```
--------------------------------
### Accessing OneSignal in Vue Component
Source: https://github.com/onesignal/onesignal-vue3/blob/main/_autodocs/api-reference/debug-and-composable.md
Illustrates how to access the OneSignal SDK instance within a Vue component after the plugin has been installed globally.
```typescript
// In component
this.$OneSignal.Notifications.addEventListener('click', handler)
```
--------------------------------
### Access OneSignal in Composition API
Source: https://github.com/onesignal/onesignal-vue3/blob/main/_autodocs/quick-reference.md
Use the `useOneSignal` hook to access the OneSignal instance within the Composition API's `setup` function.
```typescript
import { useOneSignal } from '@onesignal/onesignal-vue3'
export default {
setup() {
const OneSignal = useOneSignal()
// Use OneSignal here
}
}
```
--------------------------------
### Initialize OneSignal SDK
Source: https://github.com/onesignal/onesignal-vue3/blob/main/_autodocs/quick-reference.md
Initialize the SDK with basic or advanced options. It's recommended to check browser support before initializing.
```typescript
// Basic
await this.$OneSignal.init({ appId: 'xxx' })
// With options
await this.$OneSignal.init({
appId: 'xxx',
autoRegister: true,
requiresUserPrivacyConsent: true
})
// Check browser support first
if (this.$OneSignal.Notifications.isPushSupported()) {
await this.$OneSignal.init({ appId: 'xxx' })
}
```
--------------------------------
### OneSignal Vue3 Plugin Signature
Source: https://github.com/onesignal/onesignal-vue3/blob/main/_autodocs/api-reference/debug-and-composable.md
Defines the interface for the OneSignal Vue3 plugin's install method, specifying the required `app` and `options` parameters.
```typescript
interface OneSignalVuePlugin {
install(app: App, options: IInitObject): void
}
```
--------------------------------
### Complete Subscription Flow with Slidedown
Source: https://github.com/onesignal/onesignal-vue3/blob/main/_autodocs/api-reference/slidedown.md
Demonstrates a complete user subscription flow using the Slidedown prompt for push notifications. It includes checking for push notification support, adding an event listener for the subscription outcome, and displaying the prompt.
```typescript
async function initiateSubscription() {
// Check support first
if (!this.$OneSignal.Notifications.isPushSupported()) {
console.warn('Push not supported')
return
}
// Listen for outcome
this.$OneSignal.Slidedown.addEventListener('slidedownAllowClick', () => {
console.log('User subscribed!')
this.updateUI()
})
// Display the prompt
await this.$OneSignal.Slidedown.promptPush()
}
```
--------------------------------
### Get Native Notification Permission Status
Source: https://github.com/onesignal/onesignal-vue3/blob/main/MigrationGuide.md
Returns the browser's native notification permission status, which can be 'default', 'granted', or 'denied'. This is a synchronous operation.
```javascript
const nativeStatus = OneSignal.Notifications.permissionNative;
```
--------------------------------
### Initialize OneSignal with Promise (.then)
Source: https://github.com/onesignal/onesignal-vue3/blob/main/README.md
Initialize the OneSignal plugin using the `init` method and handle the promise resolution with a `.then` callback. This is an alternative to async/await for handling OneSignal loading.
```js
this.$OneSignal
.init({ appId: 'xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx' })
.then(() => {
// do other stuff
});
```
--------------------------------
### Handle OneSignal Init Failure Before Login
Source: https://github.com/onesignal/onesignal-vue3/blob/main/_autodocs/errors.md
Demonstrates how to catch initialization errors and prevent subsequent method calls like login if the SDK script failed to load. Ensure initialization succeeds before proceeding with authentication.
```typescript
try {
await this.$OneSignal.init({ appId: 'invalid' })
} catch (error) {
console.error('Init failed:', error.message)
}
// Later attempt to login
try {
await this.$OneSignal.login('user-123') // Still fails
} catch (error) {
console.error(error) // "OneSignal script failed to load."
}
```
```typescript
try {
await this.$OneSignal.init({
appId: 'xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx'
})
// Only proceed if init succeeds
await this.$OneSignal.login('user-123')
} catch (error) {
console.error('OneSignal setup failed:', error)
// Show user message or fallback
}
```
--------------------------------
### Logout on Component Unmount
Source: https://github.com/onesignal/onesignal-vue3/blob/main/_autodocs/api-reference/authentication.md
Example of logging out the user when a component is unmounted to end the session. Notifications can still be sent to the device via its anonymous push subscription.
```typescript
beforeUnmount() {
this.$OneSignal.logout()
}
```
--------------------------------
### init Function
Source: https://github.com/onesignal/onesignal-vue3/blob/main/_autodocs/api-reference/init.md
Initializes the OneSignal SDK with the provided configuration options. This function is essential for setting up OneSignal in your application and must be called before other OneSignal methods.
```APIDOC
## init Function
### Description
Initializes the OneSignal SDK and establishes the connection to OneSignal's service. This function loads the SDK, validates parameters, and prepares OneSignal for use.
### Signature
```typescript
function init(options: IInitObject): Promise
```
### Parameters
#### Path Parameters
None
#### Query Parameters
None
#### Request Body
- **options** (IInitObject) - Required - Configuration object containing appId and optional initialization parameters.
- **options.appId** (string) - Required - The OneSignal Application ID.
- **options.autoRegister** (boolean) - Optional - Whether to automatically register the user.
- **options.autoResubscribe** (boolean) - Optional - Whether to automatically resubscribe the user.
- **options.path** (string) - Optional - Path to the OneSignal service worker file.
- **options.serviceWorkerPath** (string) - Optional - Path to the OneSignal service worker script.
- **options.serviceWorkerUpdaterPath** (string) - Optional - Path to the OneSignal service worker updater script.
- **options.subdomainName** (string) - Optional - Subdomain of your OneSignal app.
- **options.allowLocalhostAsSecureOrigin** (boolean) - Optional - Allow localhost as a secure origin.
- **options.requiresUserPrivacyConsent** (boolean) - Optional - Whether user consent is required before initialization.
- **options.persistNotification** (boolean) - Optional - Whether notifications should persist on screen.
- **options.notificationClickHandlerMatch** (string) - Optional - URL match pattern for notification clicks ('exact' or 'origin').
- **options.notificationClickHandlerAction** (string) - Optional - Action when notification is clicked ('navigate' or 'focus').
- **options.scriptSrc** (string) - Optional - Custom URL for the OneSignal SDK script. Defaults to 'https://cdn.onesignal.com/sdks/web/v16/OneSignalSDK.page.js'.
- **options.welcomeNotification** (object) - Optional - Configuration for the welcome notification.
- **options.notifyButton** (object) - Optional - Configuration for the subscription bell notification.
- **options.promptOptions** (object) - Optional - Configuration for subscription prompts.
- **options.webhooks** (object) - Optional - Configuration for webhooks.
### Request Example
```json
{
"appId": "xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx",
"autoRegister": true,
"promptOptions": {
"slidedown": {
"prompts": [
{
"type": "push",
"autoPrompt": true,
"text": {
"actionMessage": "Get updates from our app",
"acceptButton": "Subscribe",
"cancelButton": "Not now"
}
}
]
}
}
}
```
### Response
#### Success Response (200)
`Promise` - Resolves when OneSignal initialization is complete.
#### Response Example
None (Promise resolves with no value)
### Throws
- `Error: OneSignal is already initialized.` - When init() is called more than once.
- `Error: You need to provide your OneSignal appId.` - When appId is missing from options.
- `Error: Document is not defined.` - When DOM is not available.
- `Error: This browser does not support Web Push notifications.` - When the browser lacks Web Push API support.
- `Error: OneSignal script failed to load.` - When the OneSignal SDK script fails to load from CDN.
```
--------------------------------
### Development Initialization and Debug Logging
Source: https://github.com/onesignal/onesignal-vue3/blob/main/_autodocs/configuration.md
Initialize the OneSignal SDK for development with localhost support and enable debug logging.
```typescript
await this.$OneSignal.init({
appId: 'your-dev-app-id',
allowLocalhostAsSecureOrigin: true,
serviceWorkerPath: '/OneSignalSDKWorker.js',
persistNotification: true
})
// Enable debug logging
this.$OneSignal.Debug.setLogLevel('debug')
```
--------------------------------
### Get User Language
Source: https://github.com/onesignal/onesignal-vue3/blob/main/_autodocs/api-reference/user.md
Retrieves the current language preference set for the user. Useful for ensuring a language is set or for conditional logic based on the user's locale.
```typescript
const lang = await this.$OneSignal.User.getLanguage()
console.log('User language:', lang)
```
```typescript
const currentLang = await this.$OneSignal.User.getLanguage()
if (!currentLang) {
this.$OneSignal.User.setLanguage('en')
}
```
--------------------------------
### Initialize OneSignal with Custom SDK URL
Source: https://github.com/onesignal/onesignal-vue3/blob/main/_autodocs/api-reference/init.md
Load the OneSignal SDK from a custom URL instead of the default CDN. This is useful for self-hosting or using a specific version of the SDK.
```typescript
await this.$OneSignal.init({
appId: 'xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx',
scriptSrc: 'https://my-cdn.example.com/OneSignalSDK.js'
})
```
--------------------------------
### Initialize OneSignal with Async/Await
Source: https://github.com/onesignal/onesignal-vue3/blob/main/_autodocs/api-reference/init.md
Initialize the OneSignal SDK using async/await syntax. This method is useful for handling initialization within asynchronous operations and includes basic error handling.
```typescript
try {
await this.$OneSignal.init({
appId: 'xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx'
})
console.log('OneSignal initialized')
} catch (error) {
console.error('Failed to initialize OneSignal:', error)
}
```
--------------------------------
### Initialize OneSignal with Welcome Notification
Source: https://github.com/onesignal/onesignal-vue3/blob/main/_autodocs/api-reference/init.md
Configure a welcome notification to be sent to users upon subscription. This snippet includes settings for the notification's title, message, and URL.
```typescript
await this.$OneSignal.init({
appId: 'xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx',
welcomeNotification: {
title: 'Welcome!',
message: 'Thanks for subscribing to notifications',
url: 'https://example.com',
disable: false
}
})
```
--------------------------------
### Request Notification Permission with useOneSignal
Source: https://github.com/onesignal/onesignal-vue3/blob/main/_autodocs/api-reference/debug-and-composable.md
Access the OneSignal SDK instance using the useOneSignal composable in Vue 3's Composition API. This example shows how to request notification permissions.
```vue
```
--------------------------------
### Handle User Consent with Privacy Policy Acknowledgment
Source: https://github.com/onesignal/onesignal-vue3/blob/main/_autodocs/api-reference/authentication.md
Example of handling user consent, including error handling, after they acknowledge a privacy policy. Consent must be given before notifications can be sent.
```typescript
async function acceptPrivacyPolicy() {
try {
await this.$OneSignal.setConsentGiven(true)
console.log('User consent recorded')
} catch (error) {
console.error('Failed to record consent:', error)
}
}
```
--------------------------------
### Guard OneSignal Initialization for Browser Environment
Source: https://github.com/onesignal/onesignal-vue3/blob/main/_autodocs/errors.md
Prevent 'Document is not defined' errors by ensuring SDK initialization only runs in a browser environment. Use onMounted for SSR safety.
```typescript
// In SSR context without proper guards
await this.$OneSignal.init({ appId: 'xxx' })
// Error: Document is not defined
```
```typescript
import {
onMounted
} from 'vue'
export default {
setup() {
onMounted(async () => {
// Safe: runs only in browser after hydration
await this.$OneSignal.init({
appId: 'xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx'
})
})
}
}
```
--------------------------------
### Handle User Logout Action
Source: https://github.com/onesignal/onesignal-vue3/blob/main/_autodocs/api-reference/authentication.md
Example of handling a user logout action, including error handling for the OneSignal logout process. Clears the external ID association for the current device.
```typescript
async function handleLogout() {
try {
await this.$OneSignal.logout()
console.log('User logged out from OneSignal')
} catch (error) {
console.error('Logout failed:', error)
}
}
```
--------------------------------
### Handle OneSignal Init Failure Before Showing Slidedown Prompt
Source: https://github.com/onesignal/onesignal-vue3/blob/main/_autodocs/errors.md
Illustrates how to guarantee the OneSignal SDK is initialized before calling the `promptPush` method for the slidedown prompt. This avoids errors if the SDK script failed to load.
```typescript
await this.$OneSignal.Slidedown.promptPush()
// Fails if init never succeeded
```
```typescript
async function showSubscriptionPrompt() {
try {
// Ensure SDK is ready
await this.$OneSignal.init({
appId: 'xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx'
})
// Now show prompt
await this.$OneSignal.Slidedown.promptPush()
} catch (error) {
console.error('Subscription prompt failed:', error)
}
}
```
--------------------------------
### Add Notification Change Event Listener
Source: https://github.com/onesignal/onesignal-vue3/blob/main/README.md
Example of how to add an event listener to react to changes in notification subscriptions. This snippet should be used within a Vue component's methods or lifecycle hooks.
```js
this.$OneSignal.Notifications.addEventListener('change', (event) => {
console.log('The notification was clicked!', event);
});
```
--------------------------------
### Configure OneSignal in Production
Source: https://github.com/onesignal/onesignal-vue3/blob/main/_autodocs/module-structure.md
In a production environment, set the log level to 'warn' for minimal logging. Initialize the SDK only if push notifications are supported, ensuring graceful failure.
```typescript
// Minimal logging
this.$OneSignal.Debug.setLogLevel('warn')
// Check support and fail gracefully
if (this.$OneSignal.Notifications.isPushSupported()) {
await this.$OneSignal.init({ appId: 'xxx' })
}
```
--------------------------------
### Initialize OneSignal
Source: https://github.com/onesignal/onesignal-vue3/blob/main/_autodocs/README.md
Initializes the OneSignal SDK with your application ID. This is a required first step before using other SDK features.
```APIDOC
## Initialize OneSignal
### Description
Initializes the OneSignal SDK with your application ID. This is a required first step before using other SDK features.
### Method
`init`
### Parameters
#### Path Parameters
None
#### Query Parameters
None
#### Request Body
- **appId** (string) - Required - Your OneSignal application ID.
### Request Example
```typescript
await this.$OneSignal.init({
appId: 'xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx'
})
```
### Response
#### Success Response
- **void** - The initialization is asynchronous and returns a Promise that resolves when complete.
#### Response Example
None (Promise resolves to void)
```
--------------------------------
### Initialize OneSignal SDK
Source: https://github.com/onesignal/onesignal-vue3/blob/main/_autodocs/README.md
Initialize the OneSignal SDK with your application ID. This is a required first step before using other OneSignal functionalities.
```typescript
await this.$OneSignal.init({
appId: 'xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx'
})
```
--------------------------------
### Queueing Methods with Deferred Loading
Source: https://github.com/onesignal/onesignal-vue3/blob/main/_autodocs/README.md
Methods can be queued on window.OneSignalDeferred while the SDK loads asynchronously. Promises resolve when the SDK becomes available.
```typescript
this.$OneSignal.User.addTag('key', 'value')
await this.$OneSignal.init({ appId: 'xxx' })
```
--------------------------------
### Handle Unsupported Browser for Web Push
Source: https://github.com/onesignal/onesignal-vue3/blob/main/_autodocs/errors.md
Catch errors when the browser lacks Web Push API support. Check browser support synchronously before initializing the SDK.
```typescript
try {
await this.$OneSignal.init({
appId: 'xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx'
})
} catch (error) {
if (error.message.includes('does not support')) {
console.warn('Push notifications not supported in this browser')
}
}
```
```typescript
// Check support synchronously
if (this.$OneSignal.Notifications.isPushSupported()) {
await this.$OneSignal.init({
appId: 'xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx'
})
} else {
console.warn('This browser does not support push notifications')
}
```
--------------------------------
### Configure Subscription Prompt Options
Source: https://github.com/onesignal/onesignal-vue3/blob/main/_autodocs/configuration.md
Customize the subscription prompt with various settings including prompt type, auto-display, delays, categories, and text. This is useful for tailoring the user experience for subscription requests.
```typescript
promptOptions: {
slidedown: {
prompts: [
{
type: 'push' | 'category' | 'sms' | 'email' | 'smsAndEmail',
autoPrompt: boolean,
delay?: {
pageViews?: number,
timeDelay?: number
},
categories?: [
{
tag: string,
label: string
}
],
text?: {
actionMessage?: string,
acceptButton?: string,
cancelButton?: string,
confirmMessage?: string,
emailLabel?: string,
negativeUpdateButton?: string,
positiveUpdateButton?: string,
smsLabel?: string,
updateMessage?: string
}
}
]
}
}
```
--------------------------------
### Listen to Notification Events
Source: https://github.com/onesignal/onesignal-vue3/blob/main/_autodocs/quick-reference.md
Sets up listeners for various notification events including click, foreground display, dismiss, and permission changes.
```typescript
setupNotificationListeners() {
// Click
this.$OneSignal.Notifications.addEventListener('click', (event) => {
console.log('Clicked:', event.notification)
// Navigate to URL
if (event.result.url) {
window.location.href = event.result.url
}
})
// Display
this.$OneSignal.Notifications.addEventListener(
'foregroundWillDisplay',
(event) => {
console.log('Displaying:', event.notification.title)
}
)
// Dismiss
this.$OneSignal.Notifications.addEventListener('dismiss', (event) => {
console.log('Dismissed:', event.notification.notificationId)
})
// Permission change
this.$OneSignal.Notifications.addEventListener(
'permissionChange',
(granted) => {
console.log('Permission:', granted)
}
)
}
```
--------------------------------
### Self-Hosted SDK Script Configuration
Source: https://github.com/onesignal/onesignal-vue3/blob/main/_autodocs/configuration.md
Configure OneSignal to load the SDK script from a self-hosted URL for CSP/COEP compliance.
```typescript
await this.$OneSignal.init({
appId: 'xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx',
scriptSrc: 'https://my-domain.example.com/sdk/OneSignalSDK.js'
})
```
--------------------------------
### Push Notification with Categories Configuration
Source: https://github.com/onesignal/onesignal-vue3/blob/main/_autodocs/configuration.md
Configure a push notification prompt that allows users to select categories for subscriptions.
```typescript
promptOptions: {
slidedown: {
prompts: [{
type: 'category',
autoPrompt: true,
categories: [
{ tag: 'news', label: 'News' },
{ tag: 'promotions', label: 'Promotions' },
{ tag: 'updates', label: 'Product Updates' }
]
}]
}
}
```
--------------------------------
### Push Subscription Namespace - optIn
Source: https://github.com/onesignal/onesignal-vue3/blob/main/_autodocs/api-reference/session-and-push.md
Enables push notifications for the user.
```APIDOC
## Push Subscription Namespace - optIn
### Description
Enables push notifications for the user.
### Signature
```typescript
function optIn(): Promise
```
### Parameters
#### Path Parameters
None
#### Query Parameters
None
#### Request Body
None
### Parameters
None
### Response
#### Success Response (void)
Resolves when push notifications are enabled.
### Throws
None explicitly documented.
```
--------------------------------
### Slidedown Namespace
Source: https://github.com/onesignal/onesignal-vue3/blob/main/_autodocs/module-structure.md
Enables the display of subscription prompts for push notifications, SMS, and email, and allows listening to prompt-related events.
```APIDOC
## Slidedown Namespace
### Description
Display subscription prompts and collect user contact info.
### Methods
- **promptPush(options?: object): Promise** - Push notification prompt.
- **promptPushCategories(options?: object): Promise** - Push with category selection.
- **promptSms(options?: object): Promise** - SMS subscription prompt.
- **promptEmail(options?: object): Promise** - Email subscription prompt.
- **promptSmsAndEmail(options?: object): Promise** - Combined SMS + email prompt.
- **addEventListener(event: string, listener: Function): void** - Listen to prompt events.
- **removeEventListener(event: string, listener: Function): void** - Remove listener.
### Events
- 'slidedownAllowClick'
- 'slidedownCancelClick'
- 'slidedownClosed'
- 'slidedownQueued'
- 'slidedownShown'
### Interface
IOneSignalSlidedown
```
--------------------------------
### Prompt for Push, SMS, and Email Subscriptions
Source: https://github.com/onesignal/onesignal-vue3/blob/main/_autodocs/api-reference/slidedown.md
Use this function to first prompt the user for push notification subscriptions, and then subsequently prompt for SMS and email subscriptions. Ensure the OneSignal SDK is initialized before calling these methods.
```typescript
// Collect all contact methods
async function collectAllChannels() {
// Get push first
await this.$OneSignal.Slidedown.promptPush()
// Then ask for SMS and email
await this.$OneSignal.Slidedown.promptSmsAndEmail()
}
```
--------------------------------
### Combined SMS and Email Prompt Configuration
Source: https://github.com/onesignal/onesignal-vue3/blob/main/_autodocs/configuration.md
Configure a single prompt that allows users to subscribe to both SMS and Email notifications.
```typescript
promptOptions: {
slidedown: {
prompts: [{
type: 'smsAndEmail',
autoPrompt: true
}]
}
}
```
--------------------------------
### Handle OneSignal Init Failure Before Requesting Notification Permission
Source: https://github.com/onesignal/onesignal-vue3/blob/main/_autodocs/errors.md
Shows how to ensure the OneSignal SDK is successfully initialized before attempting to request notification permissions. This prevents errors when the SDK script has failed to load.
```typescript
const granted = await this.$OneSignal.Notifications.requestPermission()
// May fail if init never completed successfully
```
```typescript
async function setupNotifications() {
try {
await this.$OneSignal.init({
appId: 'xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx'
})
const granted = await this.$OneSignal.Notifications.requestPermission()
return granted
} catch (error) {
console.error('Notification setup failed:', error)
return false
}
}
```
--------------------------------
### Access OneSignal in Options API
Source: https://github.com/onesignal/onesignal-vue3/blob/main/_autodocs/quick-reference.md
Initialize the OneSignal SDK within the `mounted` lifecycle hook when using the Options API.
```typescript
export default {
mounted() {
this.$OneSignal.init({ appId: 'xxx' })
}
}
```
--------------------------------
### Add User Tag with Options API
Source: https://github.com/onesignal/onesignal-vue3/blob/main/_autodocs/api-reference/debug-and-composable.md
Demonstrates how to use the OneSignal SDK within a Vue Options API component by accessing the SDK via `this.$OneSignal`.
```vue
```
--------------------------------
### OneSignal Configuration with Prompts
Source: https://github.com/onesignal/onesignal-vue3/blob/main/_autodocs/quick-reference.md
Configure OneSignal to automatically prompt users for push notification permission after a certain delay or page view. Set `autoPrompt` to `true` to enable.
```typescript
{
appId: 'xxx',
promptOptions: {
slidedown: {
prompts: [{
type: 'push',
autoPrompt: true,
delay: { pageViews: 1, timeDelay: 10 }
}]
}
}
}
```
--------------------------------
### Email Prompt Configuration
Source: https://github.com/onesignal/onesignal-vue3/blob/main/_autodocs/configuration.md
Configure a prompt for email notifications, including custom text for action messages and labels.
```typescript
promptOptions: {
slidedown: {
prompts: [{
type: 'email',
autoPrompt: true,
text: {
actionMessage: 'Get email updates',
acceptButton: 'Subscribe',
emailLabel: 'Email Address'
}
}]
}
}
```
--------------------------------
### Push Notification Prompt Configuration
Source: https://github.com/onesignal/onesignal-vue3/blob/main/_autodocs/configuration.md
Configure the default push notification prompt using the slidedown prompt type.
```typescript
promptOptions: {
slidedown: {
prompts: [{
type: 'push',
autoPrompt: true
}]
}
}
```
--------------------------------
### Manage Notifications
Source: https://github.com/onesignal/onesignal-vue3/blob/main/_autodocs/quick-reference.md
Request permission, check notification status and support, set defaults, and listen for notification events like clicks and dismissals.
```typescript
// Request permission
const granted = await this.$OneSignal.Notifications.requestPermission()
// Check permission
console.log(this.$OneSignal.Notifications.permission)
console.log(this.$OneSignal.Notifications.permissionNative)
// Check support
if (this.$OneSignal.Notifications.isPushSupported()) {
// Notifications supported
}
// Set defaults
await this.$OneSignal.Notifications.setDefaultUrl('https://example.com')
await this.$OneSignal.Notifications.setDefaultTitle('MyApp')
// Listen to events
this.$OneSignal.Notifications.addEventListener('click', (event) => {
console.log(event.notification.title)
console.log(event.result.url)
})
this.$OneSignal.Notifications.addEventListener(
'foregroundWillDisplay',
(event) => {
event.preventDefault() // Optional: prevent display
}
)
this.$OneSignal.Notifications.addEventListener('dismiss', (event) => {
console.log('Dismissed:', event.notification.notificationId)
})
```
--------------------------------
### Multi-Channel Collection Prompts
Source: https://github.com/onesignal/onesignal-vue3/blob/main/_autodocs/quick-reference.md
Prompts the user to collect push notifications, and then SMS and email subscriptions.
```typescript
async function collectAllChannels() {
try {
// Collect push
await this.$OneSignal.Slidedown.promptPush()
// Then collect SMS + Email
await this.$OneSignal.Slidedown.promptSmsAndEmail()
} catch (error) {
console.error('Channel collection failed:', error)
}
}
```
--------------------------------
### Handle Duplicate OneSignal Initialization
Source: https://github.com/onesignal/onesignal-vue3/blob/main/_autodocs/errors.md
Catch errors when calling init() more than once in the same session. Ensure init() is called only once during app startup.
```typescript
await this.$OneSignal.init({ appId: 'xxx' })
try {
await this.$OneSignal.init({ appId: 'xxx' })
} catch (error) {
console.error(error) // "OneSignal is already initialized."
}
```
--------------------------------
### Handle OneSignal Init Failure Before Sending Session Outcome
Source: https://github.com/onesignal/onesignal-vue3/blob/main/_autodocs/errors.md
Demonstrates ensuring the OneSignal SDK is initialized before sending session outcomes like purchases. This prevents errors if the SDK script failed to load.
```typescript
await this.$OneSignal.Session.sendOutcome('purchase', 49.99)
// Fails if init never succeeded
```
```typescript
async function trackPurchase(amount) {
try {
await this.$OneSignal.init({
appId: 'xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx'
})
await this.$OneSignal.Session.sendOutcome('purchase', amount)
} catch (error) {
console.error('Failed to track purchase:', error)
}
}
```
--------------------------------
### Auto Prompt Options Interface
Source: https://github.com/onesignal/onesignal-vue3/blob/main/_autodocs/types.md
Configuration options for automatically prompting users for push notification permissions. Allows forcing the prompt or choosing between native and slidedown UIs.
```typescript
interface AutoPromptOptions {
force?: boolean
forceSlidedownOverNative?: boolean
slidedownPromptOptions?: IOneSignalAutoPromptOptions
}
```
--------------------------------
### IOneSignalDebug
Source: https://github.com/onesignal/onesignal-vue3/blob/main/_autodocs/types.md
Methods for configuring debug logging levels.
```APIDOC
## IOneSignalDebug
Debug configuration.
### Methods
- **setLogLevel**(logLevel: 'trace' | 'debug' | 'info' | 'warn' | 'error'): void - Set logging verbosity
```
--------------------------------
### Minimal OneSignal Configuration
Source: https://github.com/onesignal/onesignal-vue3/blob/main/_autodocs/quick-reference.md
The most basic configuration requires only the App ID. Ensure this is replaced with your actual OneSignal App ID.
```typescript
{
appId: 'xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx'
}
```
--------------------------------
### GDPR Compliance Initialization and Consent
Source: https://github.com/onesignal/onesignal-vue3/blob/main/_autodocs/configuration.md
Initialize OneSignal with GDPR compliance settings, requiring user consent before prompting for push notifications.
```typescript
await this.$OneSignal.init({
appId: 'xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx',
requiresUserPrivacyConsent: true,
promptOptions: {
slidedown: {
prompts: [{
type: 'push',
autoPrompt: false, // Manual control only
text: {
actionMessage: 'Enable push notifications?',
acceptButton: 'Accept',
cancelButton: 'Decline'
}
}]
}
}
})
// Later, after user explicitly grants consent
await this.$OneSignal.setConsentGiven(true)
await this.$OneSignal.Slidedown.promptPush()
```
--------------------------------
### Check if Push is Supported
Source: https://github.com/onesignal/onesignal-vue3/blob/main/MigrationGuide.md
Verify if the current browser environment supports web push notifications. This is a synchronous operation.
```javascript
const isSupported = OneSignal.Notifications.isPushSupported();
```