max-web-push
v1.1.0
Published
A web push notification plugin with Firebase integration
Maintainers
Readme
max-web-push
项目简介
max-web-push 是一个基于 Firebase Cloud Messaging (FCM) 的网页推送订阅工具,适合封装为 npm 包,支持业务方自定义订阅弹窗,专注于核心订阅/取消/检测/获取 token 逻辑,适用于各类前端项目。
安装
npm install max-web-push快速开始
1. 初始化
import { WebPush } from 'max-web-push';
WebPush.init({
firebaseConfig: {
apiKey: '你的apiKey',
authDomain: '你的authDomain',
projectId: '你的projectId',
storageBucket: '你的storageBucket',
messagingSenderId: '你的messagingSenderId',
appId: '你的appId',
},
vapidKey: '你的VAPID公钥'
});2. 业务自定义订阅弹窗示例
function showCustomSubscribeDialog() {
const dialog = document.createElement('div');
dialog.innerHTML = `
<div style="position:fixed;bottom:30px;right:30px;background:#fff;padding:20px;border-radius:8px;box-shadow:0 2px 8px #0002;z-index:9999;">
<p>订阅我们的推送,获取最新消息!</p>
<button id="my-subscribe-btn">订阅</button>
<button id="my-cancel-btn">取消</button>
</div>
`;
document.body.appendChild(dialog);
document.getElementById('my-subscribe-btn')?.addEventListener('click', async () => {
const result = await WebPush.subscribe();
if (result.success) {
alert('订阅成功!');
// 可将 result.token 发送到后端
} else {
alert('订阅失败:' + (result.message || ''));
}
dialog.remove();
});
document.getElementById('my-cancel-btn')?.addEventListener('click', () => {
dialog.remove();
});
}
// 在你希望的场景调用
// showCustomSubscribeDialog();API 说明
WebPush.init(config: WebPushConfig)
初始化 firebase 配置,需在订阅前调用一次。
firebaseConfig:Firebase 控制台获取的配置对象vapidKey:Firebase 控制台 Web 推送证书公钥
WebPush.subscribe(): Promise<SubscribeResult>
注册 Service Worker 并请求通知权限,返回订阅结果和 token。
WebPush.unsubscribe(): Promise<UnsubscribeResult>
取消订阅。
WebPush.isSubscribed(): Promise<boolean>
检测当前是否已订阅。
WebPush.getToken(): Promise<string | null>
获取当前订阅 token。
Service Worker 配置
- 在你的项目
public或根目录下放置firebase-messaging-sw.js,内容如下:
importScripts('https://www.gstatic.com/firebasejs/9.6.1/firebase-app-compat.js');
importScripts('https://www.gstatic.com/firebasejs/9.6.1/firebase-messaging-compat.js');
firebase.initializeApp({
apiKey: '你的apiKey',
authDomain: '你的authDomain',
projectId: '你的projectId',
storageBucket: '你的storageBucket',
messagingSenderId: '你的messagingSenderId',
appId: '你的appId',
});
const messaging = firebase.messaging();
messaging.onBackgroundMessage(function(payload) {
const notificationTitle = payload.notification.title;
const notificationOptions = {
body: payload.notification.body,
// icon: '你的icon.png'
};
self.registration.showNotification(notificationTitle, notificationOptions);
});- 保证
WebPush.init和 sw 文件中的 firebaseConfig 保持一致。 - sw 文件路径需与
registerServiceWorker默认路径一致,或在subscribe前自定义注册路径。
常见问题
订阅报错 InvalidAccessError?
- 检查 VAPID 公钥格式,确保为 Firebase 控制台生成的公钥。
- 只在主线程 JS 里调用
subscribe,不要在 Service Worker 里调用。
推送没反应?
- 检查浏览器通知权限、F12 控制台、Service Worker 注册情况。
- 必须 HTTPS。
发布 npm 包
本项目使用 rollup 打包,支持 CommonJS 和 ES Module 两种模块格式。发布前请确保:
- 更新
package.json中的版本号。 - 运行
npm run build生成dist目录下的打包文件。 - 执行
npm publish发布到 npm 仓库。
License
MIT
