# Referencia de la API del plugin de Cordova

```txt title="example"
var pushwoosh = cordova.require("pushwoosh-cordova-plugin.PushNotification");

// Debe llamarse antes de pushwoosh.onDeviceReady
document.addEventListener('push-notification', function(event) {
	var notification = event.notification;
	// maneje la apertura del push aquí
});

// Inicializa Pushwoosh. Esto activará todas las notificaciones push pendientes al inicio.
pushwoosh.onDeviceReady({
	appid: "XXXXX-XXXXX",
	serviceName: "XXXX"
});

pushwoosh.registerDevice(
	function(status) {
		var pushToken = status.pushToken;
    	// maneje el registro exitoso aquí
  },
  function(status) {
    // maneje el error de registro aquí
  }
);
```

## onDeviceReady

```javascript
PushNotification.prototype.onDeviceReady = function( config )
```

_\[android, ios, wp8, windows]_\
Inicializa el plugin de Pushwoosh y activa un mensaje push de inicio. Debe llamarse en cada lanzamiento de la aplicación.

`config.appid` – Código de la aplicación de Pushwoosh.

`config.serviceName` – Nombre del servicio MPNS para la plataforma wp8.

```txt title="example"
// inicializa Pushwoosh con appid : "PUSHWOOSH_APP_ID", serviceName : "WINDOWS_PHONE_SERVICE". Esto activará todas las notificaciones push pendientes al inicio.
pushwoosh.onDeviceReady({
    appid : "XXXXX-XXXXX",
    serviceName: "XXXX"
});
```

## registerDevice

```javascript
PushNotification.prototype.registerDevice = function( success, fail )
```

_\[android, ios, wp8, windows]_\
Registra el dispositivo para notificaciones push y obtiene un token push.

`success` – callback de éxito. El token push se pasa como parámetro “status.pushToken” a este callback

`fail` – callback de error

```txt title="example"
pushwoosh.registerDevice(
    function(status) {
        alert("Registered with push token: " + status.pushToken);
    },
    function(error) {
        alert("Failed to register: " +  error);
    }
);
```

## unregisterDevice

```javascript
PushNotification.prototype.unregisterDevice = function(	success, fail	)
```

_\[android, ios, wp8, windows]_\
Anula el registro del dispositivo para dejar de recibir notificaciones push.

`success` – callback de éxito

`fail` – callback de error

## setTags

```javascript
PushNotification.prototype.setTags = function(	config, success, fail	)
```

_\[android, ios, wp8, windows]_\
Establece etiquetas para el dispositivo.

**Parámetros**

`config` – objeto con etiquetas de dispositivo personalizadas

`success` – callback de éxito. El token push se pasa como parámetro “status.pushToken” a este callback

`fail` – callback de error

```txt title="example"
// establece las etiquetas: “deviceName” con el valor “hello” y “deviceId” con el valor 10
pushwoosh.setTags({deviceName:"hello", deviceId:10},
    function() {
        console.warn('setTags success');
    },
    function(error) {
        console.warn('setTags failed');
    }
);

// establece las etiquetas de lista "MyTag" con los valores (array) "hello", "world"
pushwoosh.setTags({"MyTag":["hello", "world"]});
```

## getTags

```javascript
PushNotification.prototype.getTags = function(	success, fail	)
```

_\[android, ios, wp8, windows]_\
Devuelve las etiquetas del dispositivo, incluidas las etiquetas predeterminadas.

`success` – callback de éxito. Recibe las etiquetas como parámetros

`fail` – callback de error

```javascript
pushwoosh.getTags(
    function(tags) {
        console.warn('tags for the device: ' + JSON.stringify(tags));
    },
    function(error) {
        console.warn('get tags error: ' + JSON.stringify(error));
    }
);
```

## getPushToken

```javascript
PushNotification.prototype.getPushToken = function(	success	)
```

_\[android, ios, wp8, windows]_\
Devuelve el token push si está disponible. Tenga en cuenta que el token también llega en el callback de la función registerDevice.

`success` – callback de éxito.

```javascript
pushwoosh.getPushToken(
    function(token) {
        console.warn('push token: ' + token);
    }
);
```

## getPushwooshHWID

```javascript
PushNotification.prototype.getPushwooshHWID = function(	success	)
```

_\[android, ios, wp8, windows]_\
Devuelve el HWID de Pushwoosh utilizado para las comunicaciones con la API de Pushwoosh.

`success` – callback de getPushwooshHWID

```
pushwoosh.getPushwooshHWID(
    function(token) {
        console.warn('Pushwoosh HWID: ' + token);
    }
);
```

## getRemoteNotificationStatus

```javascript
PushNotification.prototype.getRemoteNotificationStatus = function(	callback, error	)
```

_\[android, ios]_\
Devuelve el estado detallado de los permisos de notificación push.

`callback` – callback de éxito. Recibe un objeto con las siguientes propiedades:

```
{
  "enabled" : indicador de notificaciones habilitadas.
  "pushBadge" : permiso de badges concedido. (solo iOS)
  "pushAlert" : permiso de alerta concedido. (solo iOS)
  "pushSound" : permiso de sonido concedido. (solo iOS)
}
```

`error` — callback de error

## setApplicationIconBadgeNumber

```javascript
PushNotification.prototype.setApplicationIconBadgeNumber = function(	badgeNumber	)
```

_\[android, ios]_\
Establece el número del badge en el ícono de la aplicación.

`badgeNumber` – número del badge del ícono

## getApplicationIconBadgeNumber

```javascript
PushNotification.prototype.getApplicationIconBadgeNumber = function(	callback	)
```

_\[android, ios]_\
Devuelve el número del badge del ícono de la aplicación.

`callback` – callback de éxito

```
pushwoosh.getApplicationIconBadgeNumber(function(badge){ alert(badge);} );
```

## addToApplicationIconBadgeNumber

```javascript
PushNotification.prototype.addToApplicationIconBadgeNumber = function( badgeNumber )
```

_\[android, ios]_\
Añade un valor al badge del ícono de la aplicación.

`badgeNumber` — número incremental del badge del ícono

## getLaunchNotification

```javascript
PushNotification.prototype.getLaunchNotification = function(	callback	)
```

_\[android, ios]_\
Devuelve el payload de la notificación push si la aplicación se inició en respuesta a una notificación push, o null.

`callback` – callback de éxito

## clearLaunchNotification

```javascript
PushNotification.prototype.clearLaunchNotification = function(	callback	)
```

_\[android, ios]_\
Borra la notificación de lanzamiento, getLaunchNotification() devolverá null después de esta llamada.

## setUserId

```javascript
PushNotification.prototype.setUserId = function(	userId	)
```

_\[android, ios]_\
Establece el identificador de usuario (User ID): un ID de Facebook, nombre de usuario, correo electrónico o cualquier otro ID de usuario. Esto permite que los datos y eventos se asocien a través de múltiples dispositivos de un usuario.

`userId` – identificador de usuario en formato de cadena

## postEvent

```javascript
PushNotification.prototype.postEvent = function( event, attributes )
```

_\[android, ios]_\
Publica eventos para los In-App Messages. Esto puede activar la visualización de un In-App Message según lo especificado en el Panel de Control de Pushwoosh.

`event` – evento a activar

`attributes` – objeto con atributos de evento adicionales

```
pushwoosh.setUserId("XXXXXX");
pushwoosh.postEvent("buttonPressed", { "buttonNumber" : 4, "buttonLabel" : "banner" });
```

## createLocalNotification

```javascript
PushNotification.prototype.createLocalNotification = function( config, success, fail )
```

_\[android, ios]_\
Programa una notificación local.

`config.msg` – mensaje de la notificación

`config.seconds` – retraso de la notificación en segundos

`config.userData` – datos adicionales para pasar en la notificación

`success` – callback de éxito

`fail` – callback de error

```
pushwoosh.createLocalNotification({msg:"Your pumpkins are ready!", seconds:30, userData:{}})
```

## clearLocalNotification

```javascript
PushNotification.prototype.clearLocalNotification = function()
```

_\[android]_\
Borra todas las notificaciones locales pendientes creadas por createLocalNotification

## clearNotificationCenter

```javascript
PushNotification.prototype.clearNotificationCenter = function()
```

_\[android]_\
Borra todas las notificaciones presentadas en el Centro de Notificaciones de Android.

## setMultiNotificationMode

```javascript
PushNotification.prototype.setMultiNotificationMode = function( success, fail )
```

_\[android]_\
Permite que se muestren múltiples notificaciones en el Centro de Notificaciones de Android.

## setSingleNotificationMode

```javascript
PushNotification.prototype.setSingleNotificationMode = function(	success,
fail	)
```

_\[android]_\
Permite que solo la última notificación se muestre en el Centro de Notificaciones de Android.

## setSoundType

```javascript
PushNotification.prototype.setSoundType = function( type, success, fail )
```

_\[android]_\
Establece el sonido predeterminado para los pushes entrantes.

`type` – Tipo de sonido (0 – predeterminado, 1 – sin sonido, 2 – siempre)

## setVibrateType

```javascript
PushNotification.prototype.setVibrateType = function(type, success, fail )
```

_\[android]_\
Establece el modo de vibración predeterminado para los pushes entrantes.

`type` – Tipo de vibración (0 – predeterminada, 1 – sin vibración, 2 – siempre)

## setLightScreenOnNotification

```javascript
PushNotification.prototype.setLightScreenOnNotification = function( on, success, fail )
```

_\[android]_\
Enciende la pantalla cuando llega una notificación.

`on` – habilitar/deshabilitar el desbloqueo de pantalla (deshabilitado por defecto)

## setEnableLED

```javascript
PushNotification.prototype.setEnableLED = function( on, success, fail )
```

_\[android]_\
Habilita el parpadeo del LED cuando llega una notificación y la pantalla está apagada.

`on` – habilitar/deshabilitar el parpadeo del LED (deshabilitado por defecto)

## setColorLED

```javascript
PushNotification.prototype.setColorLED = function( color, success, fail )
```

_\[android]_\
Establece el color del LED. Usar con [setEnableLED](#setenableled).

`color` – Color del LED en formato entero ARGB

## getPushHistory

```javascript
PushNotification.prototype.getPushHistory = function(	success	)
```

_\[android]_\
Devuelve un array de las notificaciones push recibidas.

`success` – callback de éxito

```
pushwoosh.getPushHistory(function(pushHistory) {
    if(pushHistory.length == 0)
        alert("no push history");
    else
        alert(JSON.stringify(pushHistory));
});

pushwoosh.clearPushHistory();
```

## clearPushHistory

```javascript
PushNotification.prototype.clearPushHistory = function()
```

_\[android]_\
Borra el historial de pushes.

## cancelAllLocalNotifications

```javascript
PushNotification.prototype.cancelAllLocalNotifications = function( callback )
```

_\[ios]_\
Borra todas las notificaciones locales del centro de notificaciones.

## presentInboxUI

_\[android, ios]_\
Abre la pantalla de [Bandeja de entrada](/es/developer/guides/message-inbox/mobile-message-inbox).

```javascript
PushNotification.prototype.presentInboxUI = function()
```

## setCommunicationEnabled

Un método binario que habilita/deshabilita toda la comunicación con Pushwoosh. El valor booleano **false** anula la suscripción del dispositivo para dejar de recibir notificaciones push y detiene la descarga de mensajes in-app. El valor **true** invierte el efecto.

```javascript
PushNotification.prototype.setCommunicationEnabled = function(enable, success, fail)
```

## removeAllDeviceData

Elimina todos los datos sobre el dispositivo.

```javascript
PushNotification.prototype.removeAllDeviceData = function()
```

## push-receive

_\[android, ios]_\
Evento de recepción de notificación push. Se activa cuando la aplicación recibe una notificación push en primer o segundo plano. Las aplicaciones cerradas no reciben este evento.

**Propiedades del evento**

`message` – (`string`) Mensaje de la notificación push

`userdata` – (`object`/`array`) Datos personalizados de la notificación push

`onStart` – (`boolean`) Es una notificación de lanzamiento

`foreground` – (`boolean`) La notificación se recibió en primer plano

`android` – (`object`) Payload de notificación específico de Android

`ios` – (`object`) Payload de notificación específico de iOS

`windows` – (`object`) Payload de notificación específico de Windows

```
document.addEventListener('push-receive',
	function(event) {
		var userData = event.notification.userdata;

		if (typeof(userData) != "undefined") {
			// maneje los datos de notificación personalizados
			console.warn('user data: ' + JSON.stringify(userData));
		}
	}
);
```

## Notificaciones en primer plano

Por defecto, el plugin de Pushwoosh no muestra notificaciones en primer plano y activa automáticamente el evento `push-receive`. Consulte la [guía de personalización del plugin](/es/developer/pushwoosh-sdk/cross-platform-frameworks/cordova/customizing-cordova-plugin/) para controlar este comportamiento.

### push-notification

_\[android, ios, wp8, windows]_\
Evento de aceptación de notificación push. Se activa cuando el usuario toca la notificación push.

```
document.addEventListener('push-notification',
	function(event) {
		var message = event.notification.message;
		var userData = event.notification.userdata;

		if (typeof(userData) != "undefined") {
			console.warn('user data: ' + JSON.stringify(userData));
		}
	}
);
```

**Propiedades del evento**

Igual que en [push-receive](#push-receive)

### additionalAuthorizationOptions

_\[solo ios]_\
Proporciona [opciones de autorización de notificación](https://developer.apple.com/documentation/usernotifications/unauthorizationoptions?language=objc) _a_dicionales. Debe llamarse antes de llamar a **registerDevice**.

```
pushwoosh.additionalAuthorizationOptions({ 
	"UNAuthorizationOptionCriticalAlert" : 1,
	"UNAuthorizationOptionProvisional": 0 // establezca 0 o no especifique la opción si no desea agregarla a su aplicación. 
});
```