Skip to content

Instantly share code, notes, and snippets.

@markwylde
Created March 29, 2021 05:12
Show Gist options
  • Save markwylde/1164ec3ba82f98dc470a6a24ebf8d933 to your computer and use it in GitHub Desktop.
Save markwylde/1164ec3ba82f98dc470a6a24ebf8d933 to your computer and use it in GitHub Desktop.
Cordova notifications
function checkNotificationPermission (requested) {
FirebasePlugin.hasPermission(function (hasPermission) {
if (hasPermission) {
console.log('Remote notifications permission granted')
// Granted
getToken()
} else if (!requested) {
// Request permission
console.log('Requesting remote notifications permission')
FirebasePlugin.grantPermission(checkNotificationPermission.bind(this, true))
} else {
// Denied
console.log("Notifications won't be shown as permission is denied")
}
})
}
const getID = function () {
FirebasePlugin.getId(function (id) {
console.log('Got FCM ID: ' + id)
}, function (error) {
console.log('Failed to get FCM ID', error)
})
}
const getToken = function () {
FirebasePlugin.getToken(function (token) {
console.log('Got FCM token: ' + token)
}, function (error) {
console.log('Failed to get FCM token', error)
})
}
const handleNotificationMessage = function (message) {
let title
if (message.title) {
title = message.title
} else if (message.notification && message.notification.title) {
title = message.notification.title
} else if (message.aps && message.aps.alert && message.aps.alert.title) {
title = message.aps.alert.title
}
let body
if (message.body) {
body = message.body
} else if (message.notification && message.notification.body) {
body = message.notification.body
} else if (message.aps && message.aps.alert && message.aps.alert.body) {
body = message.aps.alert.body
}
let msg = 'Notification message received'
if (message.tap) {
msg += ' (tapped in ' + message.tap + ')'
}
if (title) {
msg += '; title=' + title
}
if (body) {
msg += '; body=' + body
}
msg += ': ' + JSON.stringify(message)
console.log(msg)
}
function setupNotifications () {
console.log('Setting up notifications')
if (!window.cordova) {
return
}
console.log('Actualy Setting up notifications')
FirebasePlugin.onMessageReceived(function (message) {
try {
console.log('onMessageReceived')
console.dir(message)
if (message.messageType === 'notification') {
handleNotificationMessage(message)
}
} catch (e) {
console.log('Exception in onMessageReceived callback: ' + e.message)
}
}, function (error) {
console.log('Failed receiving FirebasePlugin message', error)
})
checkNotificationPermission(false) // Check permission then get token
if (cordova.platformId === 'ios') {
FirebasePlugin.onApnsTokenReceived(function (token) {
console.log('APNS token received: ' + token)
}, function (error) {
console.log('Failed to receive APNS token', error)
})
}
}
module.exports = setupNotifications
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment