メインコンテンツまでスキップ
バージョン: v8

@capacitor/push-notifications

プッシュ通知APIは、ネイティブなプッシュ通知へのアクセスを提供します。

Install

npm install @capacitor/push-notifications
npx cap sync

iOS

iOSでは、Push Notificationsケイパビリティを有効にする必要があります。ケイパビリティを有効にする方法についてはケイパビリティの設定を参照してください。

Push Notificationsケイパビリティを有効にした後、アプリのAppDelegate.swiftに以下を追加します:

func application(_ application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data) {
NotificationCenter.default.post(name: .capacitorDidRegisterForRemoteNotifications, object: deviceToken)
}

func application(_ application: UIApplication, didFailToRegisterForRemoteNotificationsWithError error: Error) {
NotificationCenter.default.post(name: .capacitorDidFailToRegisterForRemoteNotifications, object: error)
}

Android

Push Notification APIは通知を処理するためにFirebase Cloud Messaging SDKを使用します。AndroidでFirebase Cloud Messagingクライアントアプリをセットアップするを参照し、Firebaseプロジェクトの作成とアプリケーションの登録の手順に従ってください。Firebase SDKをアプリに追加したり、アプリマニフェストを編集したりする必要はありません - Push Notificationsがそれを提供します。必要なのは、Firebaseプロジェクトのgoogle-services.jsonファイルをアプリのモジュール(アプリレベル)ディレクトリに追加することだけです。

Android 13では、プッシュ通知を受信するためにパーミッションチェックが必要です。SDK 33をターゲットにする場合は、checkPermissions()requestPermissions()を適切に呼び出す必要があります。

Android 15以降、ユーザーはプライベートスペースにアプリをインストールできます。ユーザーはいつでもプライベートスペースをロックでき、ユーザーがロックを解除するまでプッシュ通知は表示されません。

アプリがプライベートスペースにインストールされているかどうかを検出することはできません。そのため、アプリが重要な通知を表示する場合は、プライベートスペースにアプリをインストールしないようユーザーに通知してください。

プライベートスペースに関連するアプリの動作変更の詳細については、Androidドキュメントを参照してください。

Variables

このプラグインは以下のプロジェクト変数(アプリの variables.gradle ファイルで定義)を使用します:

  • firebaseMessagingVersion: com.google.firebase:firebase-messaging のバージョン(デフォルト: 25.0.1

プッシュ通知アイコン

Androidでは、適切な名前のプッシュ通知アイコンをAndroidManifest.xmlファイルに追加する必要があります:

<meta-data android:name="com.google.firebase.messaging.default_notification_icon" android:resource="@mipmap/push_icon_name" />

アイコンが指定されていない場合、Androidはアプリケーションアイコンを使用しますが、プッシュアイコンは透明な背景に白いピクセルである必要があります。アプリケーションアイコンは通常そのようになっていないため、白い正方形または円が表示されます。そのため、プッシュ通知用に別のアイコンを提供することをお勧めします。

Android Studioにはプッシュ通知アイコンを作成するために使用できるアイコンジェネレーターがあります。

プッシュ通知チャンネル

Android 8.0(APIレベル26)以降では、通知チャンネルがサポートされ、推奨されています。SDKは以下の順序で受信プッシュ通知のchannelIdを決定します:

  1. まず、受信通知にchannelIdが設定されているかどうかを確認します。 FCMダッシュボードまたはAPIからプッシュ通知を送信する際に、channelIdを指定できます。
  2. 次に、AndroidManifest.xmlで指定された値があるかどうかを確認します。 独自のデフォルトチャンネルを作成して使用する場合は、default_notification_channel_idを通知チャンネルオブジェクトのIDに設定します。FCMは受信メッセージで通知チャンネルが明示的に設定されていない場合にこの値を使用します。
<meta-data
android:name="com.google.firebase.messaging.default_notification_channel_id"
android:value="@string/default_notification_channel_id" />
  1. 最後に、Firebase SDKが提供するフォールバックchannelIdを使用します。 FCMは基本設定のデフォルト通知チャンネルをすぐに使用できるように提供します。このチャンネルは、最初のプッシュメッセージを受信したときにFirebase SDKによって作成されます。

警告 オプション1または2を使用する場合でも、選択したオプションで使用されるIDと一致するIDを持つ通知チャンネルをコードで作成する必要があります。これにはcreateChannel(...)を使用できます。これを行わないと、SDKはオプション3にフォールバックします。

フォアグラウンドでのプッシュ通知の表示

アプリがフォアグラウンドにあるときのプッシュ通知の表示方法を設定できます。

プロパティ説明Since
presentationOptionsPresentationOption[]組み合わせ可能な文字列の配列です。配列の可能な値: - badge: アプリアイコンのバッジカウントが更新されます(デフォルト値) - sound: プッシュ通知を受信するとデバイスが鳴動/振動します - alert: プッシュ通知がネイティブダイアログで表示されます。オプションが不要な場合は空の配列を指定できます。badgeはiOSのみで使用可能です。1.0.0

設定例

capacitor.config.jsonでの設定:

{
"plugins": {
"PushNotifications": {
"presentationOptions": ["badge", "sound", "alert"]
}
}
}

capacitor.config.tsでの設定:

/// <reference types="@capacitor/push-notifications" />

import { CapacitorConfig } from '@capacitor/cli';

const config: CapacitorConfig = {
plugins: {
PushNotifications: {
presentationOptions: ["badge", "sound", "alert"],
},
},
};

export default config;

サイレントプッシュ通知 / データのみの通知

iOS

このプラグインはiOSサイレントプッシュ(リモート通知)をサポートしていません。これらのタイプの通知を処理するには、ネイティブコードソリューションを使用することをお勧めします。アプリへのバックグラウンド更新のプッシュを参照してください。

Android

このプラグインはデータのみの通知をサポートしていますが、アプリが強制終了されている場合はpushNotificationReceivedを呼び出しません。このシナリオを処理するには、FirebaseMessagingServiceを拡張するサービスを作成する必要があります。FCMメッセージの処理を参照してください。

よくある問題

Androidでは、プッシュ通知の配信に影響を与える可能性のある様々なシステムとアプリの状態があります:

  • デバイスがDozeモードに入った場合、アプリケーションの機能が制限される可能性があります。通知が受信される可能性を高めるには、FCM高優先度メッセージの使用を検討してください。
  • 開発と本番では動作に違いがあります。Android Studioから起動せずにアプリをテストしてみてください。詳細はこちらをご覧ください。

Example

import { PushNotifications } from '@capacitor/push-notifications';

const addListeners = async () => {
await PushNotifications.addListener('registration', token => {
console.info('Registration token: ', token.value);
});

await PushNotifications.addListener('registrationError', err => {
console.error('Registration error: ', err.error);
});

await PushNotifications.addListener('pushNotificationReceived', notification => {
console.log('Push notification received: ', notification);
});

await PushNotifications.addListener('pushNotificationActionPerformed', notification => {
console.log('Push notification action performed', notification.actionId, notification.inputValue);
});
}

const registerNotifications = async () => {
let permStatus = await PushNotifications.checkPermissions();

if (permStatus.receive === 'prompt') {
permStatus = await PushNotifications.requestPermissions();
}

if (permStatus.receive !== 'granted') {
throw new Error('User denied permissions!');
}

await PushNotifications.register();
}

const getDeliveredNotifications = async () => {
const notificationList = await PushNotifications.getDeliveredNotifications();
console.log('delivered notifications', notificationList);
}

API

register()

register() => Promise<void>

Register the app to receive push notifications.

This method will trigger the 'registration' event with the push token or 'registrationError' if there was a problem. It does not prompt the user for notification permissions, use requestPermissions() first.

Since: 1.0.0


unregister()

unregister() => Promise<void>

Unregister the app from push notifications.

This will delete a firebase token on Android, and unregister APNS on iOS.

Since: 5.0.0


getDeliveredNotifications()

getDeliveredNotifications() => Promise<DeliveredNotifications>

Get a list of notifications that are visible on the notifications screen.

Returns:

Promise<DeliveredNotifications>

Since: 1.0.0


removeDeliveredNotifications(...)

removeDeliveredNotifications(delivered: DeliveredNotifications) => Promise<void>

Remove the specified notifications from the notifications screen.

ParamType
delivered
DeliveredNotifications

Since: 1.0.0


removeAllDeliveredNotifications()

removeAllDeliveredNotifications() => Promise<void>

Remove all the notifications from the notifications screen.

Since: 1.0.0


createChannel(...)

createChannel(channel: Channel) => Promise<void>

Create a notification channel.

Only available on Android O or newer (SDK 26+).

ParamType
channel
Channel

Since: 1.0.0


deleteChannel(...)

deleteChannel(args: { id: string; }) => Promise<void>

Delete a notification channel.

Only available on Android O or newer (SDK 26+).

ParamType
args{ id: string; }

Since: 1.0.0


listChannels()

listChannels() => Promise<ListChannelsResult>

List the available notification channels.

Only available on Android O or newer (SDK 26+).

Returns:

Promise<ListChannelsResult>

Since: 1.0.0


checkPermissions()

checkPermissions() => Promise<PermissionStatus>

Check permission to receive push notifications.

On Android 12 and below the status is always granted because you can always receive push notifications. If you need to check if the user allows to display notifications, use local-notifications plugin.

Returns:

Promise<PermissionStatus>

Since: 1.0.0


requestPermissions()

requestPermissions() => Promise<PermissionStatus>

Request permission to receive push notifications.

On Android 12 and below it doesn't prompt for permission because you can always receive push notifications.

On iOS, the first time you use the function, it will prompt the user for push notification permission and return granted or denied based on the user selection. On following calls it will get the current status of the permission without prompting again.

Returns:

Promise<PermissionStatus>

Since: 1.0.0


addListener('registration', ...)

addListener(eventName: 'registration', listenerFunc: (token: Token) => void) => Promise<PluginListenerHandle>

Called when the push notification registration finishes without problems.

Provides the push notification token.

ParamType
eventName'registration'
listenerFunc
(token: Token) => void

Returns:

Promise<PluginListenerHandle>

Since: 1.0.0


addListener('registrationError', ...)

addListener(eventName: 'registrationError', listenerFunc: (error: RegistrationError) => void) => Promise<PluginListenerHandle>

Called when the push notification registration finished with problems.

Provides an error with the registration problem.

ParamType
eventName'registrationError'
listenerFunc
(error: RegistrationError) => void

Returns:

Promise<PluginListenerHandle>

Since: 1.0.0


addListener('pushNotificationReceived', ...)

addListener(eventName: 'pushNotificationReceived', listenerFunc: (notification: PushNotificationSchema) => void) => Promise<PluginListenerHandle>

Called when the device receives a push notification.

ParamType
eventName'pushNotificationReceived'
listenerFunc
(notification: PushNotificationSchema) => void

Returns:

Promise<PluginListenerHandle>

Since: 1.0.0


addListener('pushNotificationActionPerformed', ...)

addListener(eventName: 'pushNotificationActionPerformed', listenerFunc: (notification: ActionPerformed) => void) => Promise<PluginListenerHandle>

Called when an action is performed on a push notification.

ParamType
eventName'pushNotificationActionPerformed'
listenerFunc
(notification: ActionPerformed) => void

Returns:

Promise<PluginListenerHandle>

Since: 1.0.0


removeAllListeners()

removeAllListeners() => Promise<void>

Remove all native listeners for this plugin.

Since: 1.0.0


Interfaces

DeliveredNotifications

PropTypeDescriptionSince
notificationsPushNotificationSchema[]List of notifications that are visible on the notifications screen.1.0.0

PushNotificationSchema

PropTypeDescriptionSince
titlestringThe notification title.1.0.0
subtitlestringThe notification subtitle.1.0.0
bodystringThe main text payload for the notification.1.0.0
idstringThe notification identifier.1.0.0
tagstringThe notification tag. Only available on Android (from push notifications).4.0.0
badgenumberThe number to display for the app icon badge.1.0.0
notificationanyIt's not being returned.1.0.0
dataanyAny additional data that was included in the push notification payload.1.0.0
click_actionstringThe action to be performed on the user opening the notification. Only available on Android.1.0.0
linkstringDeep link from the notification. Only available on Android.1.0.0
groupstringSet the group identifier for notification grouping. Only available on Android. Works like threadIdentifier on iOS.1.0.0
groupSummarybooleanDesignate this notification as the summary for an associated group. Only available on Android.1.0.0

Channel

PropTypeDescriptionDefaultSince
idstringThe channel identifier.1.0.0
namestringThe human-friendly name of this channel (presented to the user).1.0.0
descriptionstringThe description of this channel (presented to the user).1.0.0
soundstringThe sound that should be played for notifications posted to this channel. Notification channels with an importance of at least 3 should have a sound. The file name of a sound file should be specified relative to the android app res/raw directory.1.0.0
importance
Importance
The level of interruption for notifications posted to this channel.
3
1.0.0
visibility
Visibility
The visibility of notifications posted to this channel. This setting is for whether notifications posted to this channel appear on the lockscreen or not, and if so, whether they appear in a redacted form.1.0.0
lightsbooleanWhether notifications posted to this channel should display notification lights, on devices that support it.1.0.0
lightColorstringThe light color for notifications posted to this channel. Only supported if lights are enabled on this channel and the device supports it. Supported color formats are #RRGGBB and #RRGGBBAA.1.0.0
vibrationbooleanWhether notifications posted to this channel should vibrate.1.0.0

ListChannelsResult

PropTypeDescriptionSince
channelsChannel[]List of all the Channels created by your app.1.0.0

PermissionStatus

PropTypeDescriptionSince
receive
PermissionState
Permission state of receiving notifications.1.0.0

PluginListenerHandle

PropType
remove() => Promise<void>

Token

PropTypeDescriptionSince
valuestringOn iOS it contains the APNS token. On Android it contains the FCM token.1.0.0

RegistrationError

PropTypeDescriptionSince
errorstringError message describing the registration failure.4.0.0

ActionPerformed

PropTypeDescriptionSince
actionIdstringThe action performed on the notification.1.0.0
inputValuestringText entered on the notification action. Only available on iOS.1.0.0
notification
PushNotificationSchema
The notification in which the action was performed.1.0.0

Type Aliases

Importance

The importance level. For more details, see the Android Developer Docs

1 | 2 | 3 | 4 | 5

Visibility

The notification visibility. For more details, see the Android Developer Docs

-1 | 0 | 1

PermissionState

'prompt' | 'prompt-with-rationale' | 'granted' | 'denied'