Saltar al contenido principal

Descripción general

Las notificaciones web push te permiten enviar actualizaciones en tiempo real, recordatorios y mensajes personalizados a tus usuarios, mejorando el engagement y retención. OneSignal soporta todos los navegadores y plataformas principales, permitiéndote escribir una vez y entregar a través de: Chrome, Firefox, Edge, Safari y otros navegadores soportados.

Requisitos

  • Sitio web HTTPS: Web push no funciona en HTTP o en modos incógnito/privado.
  • Acceso al servidor: Necesitarás subir un archivo service worker a tu sitio.
  • Origen único: Web push sigue la política de mismo origen. Si tienes múltiples orígenes (dominios/subdominios), necesitarás múltiples apps OneSignal (una por origen). Para cumplir con esta limitación del navegador, puedes:
    • Redirigir tráfico a un único origen para suscripciones.
    • Crear múltiples apps OneSignal—una por origen.
Si tu equipo ya creó una cuenta con OneSignal, solicita ser invitado como rol admin para que puedas configurar la app. De lo contrario, regístrate para una cuenta gratuita en onesignal.com para comenzar!

Configurar tu app OneSignal y plataforma

En el dashboard de OneSignal:
  • Ve a Settings > Push & In-App > Web.

Activa la plataforma web en tu configuración de OneSignal

Selecciona el tipo de integración:

Sitio típico (recomendado)

Gestiona prompts y configuraciones directamente a través del dashboard de OneSignal sin codificación adicional.

WordPress

Requerido si usas WordPress con nuestro plugin oficial.

Código personalizado

Para desarrolladores que necesitan control completo sobre prompts y configuración del SDK.

Configuración del sitio

Agrega los detalles del sitio:
  • Nombre del sitio: El nombre de tu sitio y título de notificación predeterminado.
  • URL del sitio: La URL de tu sitio. Ver URL del sitio para más detalles.
  • Resuscripción automática: Habilita esto para resuscribir automáticamente a usuarios que limpian sus datos del navegador cuando regresan a tu sitio (sin nuevo prompt de permiso requerido)
  • URL de icono predeterminado: Sube una imagen PNG o JPG cuadrada de 256x256px que aparece en notificaciones y prompts. Si no se establece, usamos una campana para el icono predeterminado.

Configuración web en el dashboard de OneSignal

URL del sitio

Ingresa el origen exacto de tu sitio, ej., https://yourdomain.com. Evita usar www. si tu sitio no está configurado de esa manera. Si tienes múltiples orígenes:
  • Redirige a un único origen.
  • O configura una app OneSignal por origen.

Pruebas locales

Nuestro SDK web puede probarse en entornos localhost. Si estás probando en localhost, recomendamos configurar una app OneSignal diferente de tu app de producción.
Establece la URL DEL SITIO para que coincida exactamente con la URL de tu entorno localhost. Debe ser una URL localhost común, ejemplos:
  • http://localhost
  • https://localhost:3000
  • http://127.0.0.1
  • https://127.0.0.1:5000
Si tu localhost está usando HTTP, selecciona Tratar HTTP localhost como HTTPS para pruebas.Google Chrome trata http://localhost y http://127.0.0.1 como orígenes seguros, permitiendo integraciones HTTPS incluso en HTTP. Por esto no puedes probar otros orígenes no estándar en HTTPS localhost.

Pruebas locales en el dashboard de OneSignal

Agregar allowLocalhostAsSecureOrigin a tus opciones init de OneSignal

Al inicializar OneSignal en tu sitio localhost, agrega allowLocalhostAsSecureOrigin: true, a tus opciones init de OneSignal.Adicionalmente, si estás probando localhost en HTTPS con un certificado autofirmado, puede que tengas que pedir a Chrome que ignore certificados inválidos para pruebas con: --allow-insecure-localhost. Firefox y Safari proporcionan mecanismos integrados para agregar excepciones para certificados de seguridad.
html
  <script src="https://cdn.onesignal.com/sdks/web/v16/OneSignalSDK.page.js" defer></script>
  <script>
    window.OneSignalDeferred = window.OneSignalDeferred || [];
    OneSignalDeferred.push(function(OneSignal) {
      OneSignal.init({
        appId: "YOUR_OS_APP_ID",
        allowLocalhostAsSecureOrigin: true,
      });
    });
  </script>

Prompt de permisos

La configuración de sitio típico permite a ti o a los miembros de tu equipo agregar, eliminar y actualizar prompts de permiso a través del dashboard de OneSignal en cualquier momento.
Para detalles sobre los prompts de permiso, ver Prompts de permiso Web.

Notificación de bienvenida (opcional)

También puedes establecer una notificación de bienvenida para ser enviada a los usuarios cuando se suscriban a notificaciones push.

Configuraciones avanzadas

Características adicionales configurables en el dashboard de OneSignal.

Webhooks

Nuestro SDK web proporciona la habilidad de hacer POST de ciertos eventos web push a una URL de tu elección. Los Webhooks Web Push son una implementación separada de los Webhooks de eventos y no pueden usarse de manera intercambiable.
Ver Webhooks Web Push para más detalles.

Service workers

En la siguiente página de configuración web push, se te proporcionará el archivo service worker OneSignalSDKWorker.js. Nuestro SDK web por defecto busca este archivo en la raíz de tu sitio. Si quieres cambiar la ubicación, nombre y/o alcance del archivo service worker, aquí es donde puedes actualizar esas configuraciones.
  • Ruta a archivos service worker es la ruta al directorio donde pondrás estos archivos.
  • Nombres de archivo service worker principal y actualizador pueden ser simplemente OneSignalSDKWorker.js o si quieres renombrar este archivo. Debe usar extensión de archivo .js.
  • Alcance de registro de service worker son las páginas en las que este archivo puede funcionar. Para notificaciones push, esto no importa y fue diseñado originalmente para casos donde quieres agregar más funcionalidad al archivo service worker. Deberías establecer esto como la misma ruta que tu ubicación.

Configuración de service worker

Con este ejemplo, deberías ver el código del archivo públicamente accesible en https://yourdomain.com/push/onesignal/OneSignalSDKWorker.js
Ver Service Worker de OneSignal para más detalles.

Comportamiento de clic

Controla cómo los usuarios navegan a la URL que estableces cuando hacen clic en la notificación.
  • Si los usuarios no tienen tu sitio abierto en ninguna pestaña del navegador, y hacen clic en una notificación que los lleva a tu sitio, el navegador abrirá una nueva pestaña y navegará a la URL de la notificación.
  • Si los usuarios tienen tu sitio abierto en una o más pestañas del navegador, y hacen clic en una notificación que los lleva a tu sitio, hay varias formas posibles en que el navegador puede comportarse que puedes configurar:
    • Navegación exacta (predeterminado) - Si la URL exacta de la notificación (ej. example.com/product) coincide con una pestaña que el navegador ya tiene abierta, el navegador navegará a la URL de la notificación en esa pestaña.
    • Navegación de origen - Si el origen de la notificación (ej. example.com) coincide con una pestaña que el navegador ya tiene abierta, el navegador navegará a la URL de la notificación en esa pestaña.
    • Enfoque exacto - Si la URL exacta de la notificación (ej. example.com/product) coincide con una pestaña que el navegador ya tiene abierta, el navegador enfocará en esa pestaña, pero no refrescará la página.
    • Enfoque de origen - Si el origen de la notificación (ej. example.com) coincide con una pestaña que el navegador ya tiene abierta, el navegador enfocará en esa pestaña, pero no refrescará la página.

Persistencia

El comportamiento web push predeterminado es que aparecen en el dispositivo durante aproximadamente 5 segundos antes de moverse al Centro de notificaciones donde se mantienen durante aproximadamente 1 semana antes de ser eliminadas por el sistema operativo. Algunos dispositivos y versiones de Chrome y Edge te permiten persistir notificaciones por más tiempo en la pantalla. Esto significa que la notificación permanecerá en la pantalla hasta que el usuario interactúe con ella. Esto puede molestar a tus usuarios y no se recomienda. Además, si habilitas la persistencia afectará cómo aparecen las notificaciones a los suscriptores reduciendo el conteo de caracteres y puede afectar cómo se muestran las imágenes y botones. Al cambiarlos, entrarán en efecto solo para suscriptores que visiten el sitio con las configuraciones actualizadas. Si no ves estos cambios de opciones, necesitarás esperar

Certificado Safari (Opcional)

OneSignal proporciona automáticamente los certificados necesarios para funcionar con navegadores Safari sin costo adicional. Si ya tienes tus propios Certificados Safari Web Push, activa esta opción para subir tu Safari Web .p12 Push Certificate y contraseña.

Configuración de certificado Safari


Subir archivo service worker

Como se discutió brevemente arriba en Configuraciones avanzadas > Service workers agregaremos el archivo Service Worker OneSignalSDKWorker.js a tu sitio.

Paso de subir archivo service worker

Si no estableciste la Ruta a archivos service worker en la sección Configuraciones avanzadas > Service workers, necesitarás colocar el archivo OneSignalSDKWorker.js en la raíz de nivel superior de tu sitio. De lo contrario, necesitarás colocarlo en el directorio que estableciste.
  • Opción 1. Crear archivo en servidor y copiar código
  • Opción 2. Descargar carpeta zip y subir
  1. Crea un nuevo archivo llamado OneSignalSDKWorker.js y hazlo público.
  2. Copia y pega la siguiente declaración import en el archivo:
importScripts("https://cdn.onesignal.com/sdks/web/v16/OneSignalSDK.sw.js");
Una vez que el archivo esté en tu servidor, verifica lo siguiente para asegurarte de que funciona:
1

Verifica la ubicación

Asegúrate de que el archivo esté ubicado en la misma Ruta a archivos service worker como se estableció en Configuraciones avanzadas > Service workers. Si no actualizaste estas configuraciones, entonces deberías haber puesto el archivo en tu raíz. Por ejemplo:
  • https://yourdomain.com/OneSignalSDKWorker.js
  • https://yourdomain.com/some-subdirectory/OneSignalSDKWorker.js
2

Debe ser públicamente accesible en tu origen

El archivo OneSignalSDKWorker.js debe ser públicamente accesible y disponible en tu origen. No puede alojarse a través de un CDN o colocarse en un origen diferente con redirección.Cuando visites la URL del archivo, deberías ver el código.
3

Debe servirse con content-type: application/javascript

Este es un archivo javascript y necesita servirse como tal. No puede tener un content-type de text/html.
Si tienes preguntas adicionales o estás migrando a OneSignal desde un proveedor web push diferente, se recomienda revisar nuestra documentación Service Worker de OneSignal.

Agregar código a tu sitio

Ahora deberías estar listo para agregar nuestro SDK a tu sitio. El código JavaScript SDK que proporcionamos debería funcionar en cualquier sitio, pero si tu sitio está configurado usando Angular, React JS o Vue JS entonces sigue estos enlaces. Para inicializar OneSignal en tu sitio con nuestro JavaScript SDK, copia/pega el código proporcionado en las etiquetas <head> de tu sitio web. Nuestro dashboard proporcionará el siguiente código pero incluye tu OneSignal app ID.
JavaScript
  <script src="https://cdn.onesignal.com/sdks/web/v16/OneSignalSDK.page.js" defer></script>
  <script>
    window.OneSignalDeferred = window.OneSignalDeferred || [];
    OneSignalDeferred.push(async function(OneSignal) {
      await OneSignal.init({
        appId: "YOUR_ONESIGNAL_APP_ID",
      });
    });
  </script>

Soporte iOS web push

Apple comenzó a soportar notificaciones web push en iPhones e iPads ejecutando iOS 16.4+. A diferencia de dispositivos Android donde web push simplemente “funciona” siempre que se visite en un navegador soportado, Apple agregó algunos requisitos más como un archivo manifest.json y una acción del usuario para agregar tu sitio a su pantalla de inicio.

Configuración iOS Web Push

Agrega el archivo manifest.json requerido y guía a los usuarios para agregar tu sitio a su pantalla de inicio.

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!