Saltar al contenido principal

Descripción general

Esta guía explica cómo integrar notificaciones push de OneSignal en una aplicación Vue.js. Cubre tanto Vue 2 como Vue 3 usando los plugins oficiales Vue de OneSignal, junto con consideraciones clave de configuración incluyendo configuración de service worker y soporte de TypeScript.

Requisitos

Compatibilidad Vue

Asegúrate de instalar una versión de plugin compatible con tu entorno Vue.
VuePlugin OneSignal
2onesignal-vue
3onesignal-vue3

Instalación

Instala a través de tu gestor de paquetes preferido:
yarn add onesignal-vue
# or yarn add @onesignal/onesignal-vue3

Inicialización

Importa el servicio OneSignal e inicialízalo en tu componente raíz. La función init devuelve una promesa que se resuelve cuando OneSignal se carga. Reemplaza YOUR_APP_ID con tu ID de aplicación OneSignal que se encuentra en Keys & IDs.
import Vue from 'vue'
import OneSignalVue from 'onesignal-vue'

Vue.use(OneSignalVue);

new Vue({
  render: h => h(App),
  beforeMount() {
    this.$OneSignal.init({ appId: 'YOUR_APP_ID' });
  }
}).$mount('#app')
//Example 1
await this.$OneSignal.init({ appId: 'YOUR_APP_ID' });
// do other stuff

//Example 2
this.$OneSignal.init({ appId: 'YOUR_APP_ID' }).then(() => {
  // do other stuff
});
El plugin OneSignal expone automáticamente una propiedad global $OneSignal accesible dentro de la aplicación.

Composition API

También puedes aprovechar la Composition API de Vue a través del hook useOneSignal() que se puede llamar desde dentro de setup.

Personalizar opciones init

Puedes personalizar tu inicialización con parámetros init adicionales.

Configuración de Service Worker

Si aún no lo has hecho, necesitarás descargar el archivo Service Worker de OneSignal para agregar a tu sitio. El archivo OneSignalSDKWorker.js debe ser públicamente accesible. Puedes ponerlo en tu directorio public, raíz de nivel superior o un subdirectorio. Sin embargo, si estás colocando el archivo en un subdirectorio y/o tienes otro service worker para tu sitio, entonces asegúrate de especificar la ruta. Ver Service Worker de OneSignal para más detalles.
OpciónDescripción
serviceWorkerParamAlcance controlado por el worker de OneSignal. Recomendación: Usa una subruta personalizada (ej., "/onesignal/").
serviceWorkerPathRuta a tu archivo service worker de OneSignal alojado (ej., "onesignal/OneSignalSDKWorker.js"). Debe ser públicamente accesible.
Ejemplo:
this.$OneSignal.init({
  appId: 'YOUR-ONESIGNAL-APP-ID',
  serviceWorkerParam: {
    scope: '/onesignal/'
  },
  serviceWorkerPath: 'onesignal/OneSignalSDKWorker.js'
});

Alojar el worker

  • Raíz pública (predeterminado): /OneSignalSDKWorker.js
  • Carpeta personalizada (recomendado): ej., /onesignal/OneSignalSDKWorker.js como se estableció en el paso anterior.

Verificar alojamiento del service worker

Visita la ruta en tu navegador para confirmar que es accesible. Si usaste raíz:
https://your-site.com/OneSignalSDKWorker.js
Si usas la ruta del ejemplo:
https://your-site.com/onesignal/OneSignalSDKWorker.js
Debería devolver JavaScript válido.

Notas importantes

  • Evitar inicialización duplicada en desarrollo
    • Al probar en un entorno de desarrollo, podrías ver que el SDK de OneSignal se inicializa dos veces, lo que puede causar errores de consola.
    • Esto sucede debido a que <React.StrictMode> causa que los efectos se ejecuten dos veces en desarrollo. Para resolverlo, elimina <React.StrictMode> de tu componente raíz durante el desarrollo.
El modo estricto solo afecta el desarrollo—no impacta las compilaciones de producción.

Testing the OneSignal SDK integration

This guide helps you verify that your OneSignal SDK integration is working correctly by testing push notifications and subscription registration.

Check web push subscriptions

1

Launch your site on a test device.

  • Use Chrome, Firefox, Edge, or Safari while testing.
  • Do not use Incognito or private browsing mode. Users cannot subscribe to push notifications in these modes.
  • The prompts should appear based on your permission prompts configuration.
  • Click Allow on the native prompt to subscribe to push notifications.

Web push native permission prompt

2

Check your OneSignal dashboard

Check the OneSignal dashboard:
  • Go to Audience > Subscriptions.
  • You should see a new entry with the status Subscribed.

Dashboard showing subscription with 'Subscribed' status

You have successfully created a web push subscription. Web push subscriptions are created when users first subscribe to push notifications on your site.

Set up test subscriptions

Test subscriptions are helpful for testing a push notification before sending a message.
1

Add to Test Subscriptions.

In the dashboard, next to the subscription, click the Options (three dots) button and select Add to Test Subscriptions.

Adding a device to Test Subscriptions

2

Name your subscription.

Name the subscription so you can easily identify your device later in the Test Subscriptions tab.

Dashboard showing the 'Name your subscription' field

3

Create a test users segment.

Go to Audience > Segments > New Segment.
4

Name the segment.

Name the segment Test Users (the name is important because it will be used later).
5

Add the Test Users filter and click Create Segment.

Creating a 'Test Users' segment with the Test Users filter

You have successfully created a segment of test users. We can now test sending messages to this individual device and groups of test users.

Send test push via API

1

Get your App API Key and App ID.

In your OneSignal dashboard, go to Settings > Keys & IDs.
2

Update the provided code.

Replace YOUR_APP_API_KEY and YOUR_APP_ID in the code below with your actual keys. This code uses the Test Users segment we created earlier.
curl -X \
POST --url 'https://api.onesignal.com/notifications' \
 --header 'content-type: application/json; charset=utf-8' \
 --header 'authorization: Key YOUR_APP_API_KEY' \
 --data \
 '{
  "app_id": "YOUR_APP_ID",
  "target_channel": "push",
  "name": "Testing basic setup",
  "headings": {
  	"en": "👋"
  },
  "contents": {
    "en": "Hello world!"
  },
  "included_segments": [
    "Test Users"
  ],
  "chrome_web_image": "https://avatars.githubusercontent.com/u/11823027?s=200&v=4"
}'
3

Run the code.

Run the code in your terminal.
4

Check images and confirmed delivery.

If all setup steps were completed successfully, the test subscriptions should receive a notification.
Only Chrome supports images. Images will appear small in the collapsed notification view. Expand the notification to see the full image.

Expanded push notification with image on Chrome macOS

5

Check for confirmed delivery.

In your dashboard, go to Delivery > Sent Messages, then click the message to view stats.You should see the confirmed stat, meaning the device received the push.
Safari does not support Confirmed Delivery.

Delivery stats showing confirmed delivery

If you’re on a Professional plan or higher, scroll to Audience Activity to see subscription-level confirmation:

Confirmed delivery at the device level in Audience Activity

You have successfully sent a notification via our API to a segment.
Need help? Contact support@onesignal.com with the following information:
  • Copy-paste the API request and response into a .txt file
  • Your Subscription ID
  • Your website URL with the OneSignal code
We’ll be happy to help!

User identification

Previously, we demonstrated how to create web push Subscriptions. Now we’ll expand to identifying Users across all their subscriptions (including push, email, and SMS) using the OneSignal SDK. We’ll cover External IDs, tags, multi-channel subscriptions, privacy, and event tracking to help you unify and engage users across platforms.

Assign External ID

Use an External ID to identify users consistently across devices, email addresses, and phone numbers using your backend’s user identifier. This ensures your messaging stays unified across channels and 3rd party systems (especially important for Integrations). Set the External ID with our SDK’s login method each time they are identified by your app.
OneSignal generates unique read-only IDs for subscriptions (Subscription ID) and users (OneSignal ID).As users download your app on different devices, subscribe to your website, and/or provide you email addresses and phone numbers outside of your app, new subscriptions will be created.Setting the External ID via our SDK is highly recommended to identify users across all their subscriptions, regardless of how they are created.

Add data tags

Tags are key-value pairs of string data you can use to store user properties (like username, role, or preferences) and events (like purchase_date, game_level, or user interactions). Tags power advanced Message Personalization and Segmentation allowing for more advanced use cases. Set tags with our SDK addTag and addTags methods as events occur in your app. In this example, the user reached level 6 identifiable by the tag called current_level set to a value of 6.

A user profile in OneSignal with a tag called "current_level" set to "6"

We can create a segment of users that have a level of between 5 and 10, and use that to send targeted and personalized messages:

Segment editor showing a segment targeting users with a current_level value of greater than 4 and less than 10


Screenshot showing a push notification targeting the Level 5-10 segment with a personalized message

Add email and/or SMS subscriptions

Earlier we saw how our SDK creates web push subscriptions to send push. You can also reach users through emails and SMS channels by creating the corresponding subscriptions. If the email address and/or phone number already exist in the OneSignal app, the SDK will add it to the existing user, it will not create duplicates. You can view unified users via Audience > Users in the dashboard or with the View user API.

A user profile with push, email, and SMS subscriptions unified by External ID

Best practices for multi-channel communication
  • Obtain explicit consent before adding email or SMS subscriptions.
  • Explain the benefits of each communication channel to users.
  • Provide channel preferences so users can select which channels they prefer.

To control when OneSignal collects user data, use the SDK’s consent gating methods: See our Privacy & security docs for more on:

Listen to push, user, and in-app events

Use SDK listeners to react to user actions and state changes. The SDK provides several event listeners for you to hook into. See our SDK reference guide for more details.

Push notification events

User state changes


Advanced setup & capabilities

Explore more capabilities to enhance your integration:

Web SDK setup & reference

Make sure you’ve enabled all key features by reviewing the Web push setup guide. For full details on available methods and configuration options, visit the Web SDK reference.
Congratulations! You’ve successfully completed the Web SDK setup guide.

Need help?Chat with our Support team or email support@onesignal.comPlease include:
  • Details of the issue you’re experiencing and steps to reproduce if available
  • Your OneSignal App ID
  • The External ID or Subscription ID if applicable
  • The URL to the message you tested in the OneSignal Dashboard if applicable
  • Any relevant logs or error messages
We’re happy to help!