FCM:firebase getToken 选项(ServiceWorkerRegistration,vapidKey)

FCM: firebase getToken options( ServiceWorkerRegistration, vapidKey)

这就是 firebase 文档描述获取令牌函数的方式:

getToken ( options ? : { serviceWorkerRegistration ?: ServiceWorkerRegistration ; vapidKey ?: string } ) : Promise < string >

Optional options: { serviceWorkerRegistration?: ServiceWorkerRegistration; vapidKey?: string }

Optional serviceWorkerRegistration?: ServiceWorkerRegistration The service worker registration for receiving push messaging. If the registration is not provided explicitly, you need to have a firebase-messaging-sw.js at your root location. See Retrieve the current registration token for more details.

我只是想弄清楚如何在我的代码中使用服务工作者选项。我是否只是像这样将文件位置放在 getToken('/file-location') 中?还是导入一个函数来注册我的自定义 firebase service worker?我可能只是愚蠢,但这些文档是准系统。

如果您的 firebase-messaging-sw.js 在您的 (web) 服务器根目录中,您只需调用 .getToken(),您的 service worker 将被自动加载和使用。

如果您的 firebase-messaging-sw.js 位于 /my-other-folder,那么您需要这样称呼它:

const swRegistration = await navigator.serviceWorker.register('/my-other-folder/firebase-messaging-sw.js');
const token = await fcm.getToken({
  serviceWorkerRegistration: swRegistration,
});