You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何为Web端FCM推送通知添加启用/禁用切换功能?

Got it, let's tackle adding a toggle button to control FCM notification permissions on your web app. Here's a step-by-step solution that builds on your existing code:

Implement FCM Notification Toggle Button

1. Add a Toggle Control in HTML

First, add an intuitive toggle switch to your page so users can easily turn notifications on or off. I've included some basic CSS to make it look like a standard toggle:

<style>
/* Simple toggle switch styling */
.toggle-switch {
  display: flex;
  align-items: center;
  gap: 8px;
  cursor: pointer;
  margin: 16px;
}
.toggle-switch .slider {
  position: relative;
  width: 48px;
  height: 24px;
  background-color: #ccc;
  border-radius: 24px;
  transition: background-color 0.3s;
}
.toggle-switch .slider::before {
  content: "";
  position: absolute;
  top: 2px;
  left: 2px;
  width: 20px;
  height: 20px;
  background-color: white;
  border-radius: 50%;
  transition: transform 0.3s;
}
.toggle-switch input:checked + .slider {
  background-color: #2196F3;
}
.toggle-switch input:checked + .slider::before {
  transform: translateX(24px);
}
.toggle-switch input {
  display: none;
}
.toggle-label {
  font-size: 14px;
}
</style>

<label class="toggle-switch">
  <input type="checkbox" id="notificationToggle">
  <span class="slider"></span>
  <span class="toggle-label">Enable Notifications</span>
</label>

2. Integrate Toggle Logic with FCM

Now update your FCM initialization code to handle permission checks, toggle events, and token management. This ensures the button state always matches the actual notification status:

// Initialize Firebase (your existing config)
firebase.initializeApp(config);
const messaging = firebase.messaging();
const toggleBtn = document.getElementById('notificationToggle');
const toggleLabel = document.querySelector('.toggle-label');

// Check current notification status on page load to set initial button state
async function syncToggleState() {
  const permission = await Notification.requestPermission(); // Returns existing status if already granted/denied
  const hasActiveToken = await messaging.getToken() !== null;

  if (permission === 'granted' && hasActiveToken) {
    toggleBtn.checked = true;
    toggleLabel.textContent = 'Disable Notifications';
  } else {
    toggleBtn.checked = false;
    toggleLabel.textContent = 'Enable Notifications';
  }
}

// Handle toggle button clicks
toggleBtn.addEventListener('change', async function() {
  if (this.checked) {
    // User wants to enable notifications: request permission and get token
    try {
      const permission = await messaging.requestPermission();
      if (permission === 'granted') {
        const token = await messaging.getToken();
        console.log('Notifications enabled. Token:', token);
        // Don't forget to send this token to your backend to save it
        toggleLabel.textContent = 'Disable Notifications';
      } else {
        // User denied permission: reset toggle state
        this.checked = false;
        toggleLabel.textContent = 'Enable Notifications';
        alert('Notification permission is required to enable alerts');
      }
    } catch (error) {
      console.error('Failed to enable notifications:', error);
      this.checked = false;
      toggleLabel.textContent = 'Enable Notifications';
    }
  } else {
    // User wants to disable notifications: delete the FCM token
    try {
      const token = await messaging.getToken();
      if (token) {
        await messaging.deleteToken(token);
        console.log('Notifications disabled. Token removed.');
        // Notify your backend to remove this token from your push list
      }
      toggleLabel.textContent = 'Enable Notifications';
      // Note: We can't fully revoke permission via JS—remind user to adjust browser settings if needed
      alert('Notifications disabled. To fully revoke permission, adjust your browser notification settings.');
    } catch (error) {
      console.error('Failed to disable notifications:', error);
      this.checked = true;
      toggleLabel.textContent = 'Disable Notifications';
    }
  }
});

// Sync toggle state when the page finishes loading
window.addEventListener('load', syncToggleState);

Key Notes

  • State Sync: The syncToggleState function ensures the button matches the actual notification permission status when the page loads.
  • Token Management: When enabling, we fetch and save the FCM token; when disabling, we delete it to stop unwanted pushes.
  • User Feedback: Clear alerts and label updates keep users informed about what's happening, including the limitation that JS can't fully revoke browser permissions.

内容的提问来源于stack exchange,提问作者Gayathri Manohar

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.29 08:16:03