Referencia de la API del plugin de Cordova
var pushwoosh = cordova.require("pushwoosh-cordova-plugin.PushNotification");
// Should be called before pushwoosh.onDeviceReadydocument.addEventListener('push-notification', function(event) { var notification = event.notification; // handle push open here});
// Initialize Pushwoosh. This will trigger all pending push notifications on start.pushwoosh.onDeviceReady({ appid: "XXXXX-XXXXX", serviceName: "XXXX"});
pushwoosh.registerDevice( function(status) { var pushToken = status.pushToken; // handle successful registration here }, function(status) { // handle registration error here });onDeviceReady
Anchor link toPushNotification.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 aplicación de Pushwoosh.
config.serviceName – Nombre del servicio MPNS para la plataforma wp8.
// initialize Pushwoosh with appid : "PUSHWOOSH_APP_ID", serviceName : "WINDOWS_PHONE_SERVICE". This will trigger all pending push notifications on start.pushwoosh.onDeviceReady({ appid : "XXXXX-XXXXX", serviceName: "XXXX"});registerDevice
Anchor link toPushNotification.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.
pushwoosh.registerDevice( function(status) { alert("Registered with push token: " + status.pushToken); }, function(error) { alert("Failed to register: " + error); });unregisterDevice
Anchor link toPushNotification.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
Anchor link toPushNotification.prototype.setTags = function( config, success, fail )[android, ios, wp8, windows]
Establece tags para el dispositivo.
Parámetros
config – objeto con tags de dispositivo personalizadas.
success – callback de éxito. El token push se pasa como parámetro “status.pushToken” a este callback.
fail – callback de error.
// sets tags: “deviceName” with value “hello” and “deviceId” with value 10pushwoosh.setTags({deviceName:"hello", deviceId:10}, function() { console.warn('setTags success'); }, function(error) { console.warn('setTags failed'); });
// sets list tags "MyTag" with values (array) "hello", "world"pushwoosh.setTags({"MyTag":["hello", "world"]});getTags
Anchor link toPushNotification.prototype.getTags = function( success, fail )[android, ios, wp8, windows]
Devuelve los tags del dispositivo, incluyendo los tags por defecto.
success – callback de éxito. Recibe los tags como parámetros.
fail – callback de error.
pushwoosh.getTags( function(tags) { console.warn('tags for the device: ' + JSON.stringify(tags)); }, function(error) { console.warn('get tags error: ' + JSON.stringify(error)); });getPushToken
Anchor link toPushNotification.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.
pushwoosh.getPushToken( function(token) { console.warn('push token: ' + token); });getPushwooshHWID
Anchor link toPushNotification.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
Anchor link toPushNotification.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
Anchor link toPushNotification.prototype.setApplicationIconBadgeNumber = function( badgeNumber )[android, ios]
Establece el número del badge en el icono de la aplicación.
badgeNumber – número del badge del icono.
getApplicationIconBadgeNumber
Anchor link toPushNotification.prototype.getApplicationIconBadgeNumber = function( callback )[android, ios]
Devuelve el número del badge del icono de la aplicación.
callback – callback de éxito.
pushwoosh.getApplicationIconBadgeNumber(function(badge){ alert(badge);} );addToApplicationIconBadgeNumber
Anchor link toPushNotification.prototype.addToApplicationIconBadgeNumber = function( badgeNumber )[android, ios]
Añade un valor al badge del icono de la aplicación.
badgeNumber — número incremental del badge del icono.
getLaunchNotification
Anchor link toPushNotification.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
Anchor link toPushNotification.prototype.clearLaunchNotification = function( callback )[android, ios]
Borra la notificación de lanzamiento, getLaunchNotification() devolverá null después de esta llamada.
setUserId
Anchor link toPushNotification.prototype.setUserId = function( userId )[android, ios]
Establece el identificador de usuario: 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 los múltiples dispositivos de un usuario.
userId – identificador de cadena de usuario.
postEvent
Anchor link toPushNotification.prototype.postEvent = function( event, attributes )[android, ios]
Publica eventos para Mensajes In-App. Esto puede activar la visualización de un mensaje In-App según se especifica 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
Anchor link toPushNotification.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
Anchor link toPushNotification.prototype.clearLocalNotification = function()[android]
Borra todas las notificaciones locales pendientes creadas por createLocalNotification.
clearNotificationCenter
Anchor link toPushNotification.prototype.clearNotificationCenter = function()[android]
Borra todas las notificaciones presentadas en el Centro de Notificaciones de Android.
setMultiNotificationMode
Anchor link toPushNotification.prototype.setMultiNotificationMode = function( success, fail )[android]
Permite que se muestren múltiples notificaciones en el Centro de Notificaciones de Android.
setSingleNotificationMode
Anchor link toPushNotification.prototype.setSingleNotificationMode = function( success,fail )[android]
Permite que solo se muestre la última notificación en el Centro de Notificaciones de Android.
setSoundType
Anchor link toPushNotification.prototype.setSoundType = function( type, success, fail )[android]
Establece el sonido por defecto para los pushes entrantes.
type – Tipo de sonido (0 – por defecto, 1 – sin sonido, 2 – siempre).
setVibrateType
Anchor link toPushNotification.prototype.setVibrateType = function(type, success, fail )[android]
Establece el modo de vibración por defecto para los pushes entrantes.
type – Tipo de vibración (0 – por defecto, 1 – sin vibración, 2 – siempre).
setLightScreenOnNotification
Anchor link toPushNotification.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
Anchor link toPushNotification.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
Anchor link toPushNotification.prototype.setColorLED = function( color, success, fail )[android]
Establece el color del LED. Usar con setEnableLED.
color – Color del LED en formato entero ARGB.
getPushHistory
Anchor link toPushNotification.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
Anchor link toPushNotification.prototype.clearPushHistory = function()[android]
Borra el historial de pushes.
cancelAllLocalNotifications
Anchor link toPushNotification.prototype.cancelAllLocalNotifications = function( callback )[ios]
Borra todas las notificaciones locales del centro de notificaciones.
presentInboxUI
Anchor link to[android, ios]
Abre la pantalla de Bandeja de entrada. Acepta un objeto de estilo opcional. Consulte Configuración de la Bandeja de entrada de mensajes para Cordova para ver la lista completa de claves de estilo.
PushNotification.prototype.presentInboxUI = function( params )loadMessages
Anchor link to[android, ios]
Carga el array de mensajes de la bandeja de entrada.
PushNotification.prototype.loadMessages = function( success, fail )unreadMessagesCount
Anchor link to[android, ios]
Devuelve el número de mensajes no leídos en la bandeja de entrada.
PushNotification.prototype.unreadMessagesCount = function( success )messagesCount
Anchor link to[android, ios]
Devuelve el número total de mensajes en la bandeja de entrada.
PushNotification.prototype.messagesCount = function( success )messagesWithNoActionPerformedCount
Anchor link to[android, ios]
Devuelve el número de mensajes de la bandeja de entrada sin ninguna acción realizada.
PushNotification.prototype.messagesWithNoActionPerformedCount = function( success )readMessage
Anchor link to[android, ios]
Marca un mensaje de la bandeja de entrada como leído.
PushNotification.prototype.readMessage = function( number )deleteMessage
Anchor link to[android, ios]
Elimina un mensaje de la bandeja de entrada.
PushNotification.prototype.deleteMessage = function( number )performAction
Anchor link to[android, ios]
Realiza la acción asignada a un mensaje de la bandeja de entrada, por ejemplo, abrir una URL.
PushNotification.prototype.performAction = function( number )setCommunicationEnabled
Anchor link toUn método binario que habilita/deshabilita toda la comunicación con Pushwoosh. El valor booleano false anula la suscripción del dispositivo para recibir notificaciones push y detiene la descarga de mensajes in-app. El valor true invierte el efecto.
PushNotification.prototype.setCommunicationEnabled = function(enable, success, fail)removeAllDeviceData
Anchor link toElimina todos los datos sobre el dispositivo.
PushNotification.prototype.removeAllDeviceData = function()push-receive
Anchor link to[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") { // handle custom notification data console.warn('user data: ' + JSON.stringify(userData)); } });Notificaciones en primer plano
Anchor link toPor 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 para controlar este comportamiento.
push-notification
Anchor link to[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
additionalAuthorizationOptions
Anchor link to[solo ios]
Proporciona opciones de autorización de notificación _a_dicionales. Debe llamarse antes de llamar a registerDevice.
pushwoosh.additionalAuthorizationOptions({ "UNAuthorizationOptionCriticalAlert" : 1, "UNAuthorizationOptionProvisional": 0 // set 0 or don't specify the option if you don't want to add it to your app.});