メインコンテンツまでスキップ

6. App.tsxを作成

Firebase Cloud Messagingの初期化

前の手順で取得した値です。

src/App.tsx
import { initializeApp } from "firebase/app";
import { getMessaging } from "firebase/messaging";

const firebaseConfig = {
apiKey: "AIzaSyDjcpgUOkQKYsfahsBx-pd5rRNLMu8e2OI",
authDomain: "webpush-6b963.firebaseapp.com",
projectId: "webpush-6b963",
storageBucket: "webpush-6b963.appspot.com",
messagingSenderId: "849385313410",
appId: "1:849385313410:web:75afe5212cc8a264da109b"
};

// Initialize Firebase
const app = initializeApp(firebaseConfig);
// Initialize Firebase Cloud Messaging and get a reference to the service
const messaging = getMessaging(app);

鍵ペアの定義

前の手順で取得した値です。

src/App.tsx
const vapidKey = "BCYBsbttg4lKsLkSz3KXHdoijEKJhLWj7Au69Sp9niUUa_IwRtXAYSd7zLP52hBKG-_uf8evUTVphiMKl4CNihk"

Service Workerの登録

Service Workerを登録します。

src/App.tsx
import { ServiceWorker } from 'aws-amplify';

const serviceWorker = new ServiceWorker()
var registration: ServiceWorkerRegistration;
serviceWorker.register('/service-worker.js', '/').then((reg => registration = reg as ServiceWorkerRegistration))

権限の許可を要求

権限の許可をユーザーに求めます。

image.png

src/App.tsx
import { getToken } from "firebase/messaging";

function requestPermission() {
isSupported().then((isSupport) => {
if (!isSupport) {
console.log('Messaging is not support.');
return
}

console.log('Requesting permission...');
Notification.requestPermission().then((permission) => {
if (permission === 'granted') {
console.log('Notification permission granted.');
getTokenRequest()
}
})
})
}

デバイストークンの取得

デバイスを識別するトークンを取得します。

src/App.tsx
import { getToken } from "firebase/messaging";

function getTokenRequest() {
// Add the public key generated from the console here.
getToken(messaging, {
vapidKey: vapidKey,
serviceWorkerRegistration: registration
})
.then((currentToken) => {
if (currentToken) {
// Send the token to your server and update the UI if necessary
// ...
console.log(`token: ${currentToken}`);

setDeviceToken(currentToken)

} else {
// Show permission request UI
console.log('No registration token available. Request permission to generate one.');
// ...
}
}).catch((err) => {
console.log('An error occurred while retrieving token. ', err);
// ...
});
}

デバイストークンをAmazon Pinpointに登録

src/App.tsx
import { Analytics } from 'aws-amplify';

Analytics.updateEndpoint({
address: deviceToken,
channelType: "GCM",
optOut: 'NONE',
}).then((reason => { console.log(reason) }))

これで準備完了です。