Badge

Display a badge on the app icon

The Badge component provides an interface to the Badging API, enabling your Progressive Web App to display badges on the application icon. These badges are perfect for notifying users of new content, unread messages, pending tasks, or any other count-based information that requires attention.

This component is particularly useful for:

  • Displaying unread message or email counts

  • Showing notification counters

  • Indicating pending tasks or updates

  • Alerting users to new content availability

  • Displaying shopping cart item counts

Browser Support

The Badging API is supported in Chromium-based browsers (Chrome, Edge, Opera) on desktop and Android. The badge appears on the PWA's icon when it's installed on the device.

circle-info

Badges only appear when the PWA is installed. Users must install your app to their home screen or desktop to see badges.

Usage

Basic Badge Counter

<body {{ stimulus_controller('@pwa/badge') }}>
    <div class="notifications">
        <h2>Notifications</h2>
        <p>You have <span id="notification-count">5</span> new notifications</p>

        <button {{ stimulus_action('@pwa/badge', 'update', 'click', {counter: 5}) }}>
            Set Badge to 5
        </button>

        <button {{ stimulus_action('@pwa/badge', 'clear', 'click') }}>
            Clear Badge
        </button>
    </div>
</body>

<script>
    document.addEventListener('pwa--badge:updated', (event) => {
        console.log('Badge updated:', event.detail.counter);
    });
</script>

Dynamic Badge Update on Page Load

Real-time Badge Updates

Badge with WebSocket Updates

E-commerce Shopping Cart Badge

Parameters

None

Actions

update

Sets the badge counter to a specified value. The action requires a counter parameter.

Parameters:

  • counter (number): The value to display on the badge. Must be a positive integer.

circle-exclamation

clear

Removes the badge from the application icon.

This is useful when:

  • User has read all notifications

  • All tasks are completed

  • Shopping cart is empty

  • Any count-based metric reaches zero

Targets

None

Events

pwa--badge:updated

Dispatched whenever the badge value changes (either updated with a new count or cleared).

Payload: {counter}

  • counter (number|null): The new badge value, or null if the badge was cleared

Example:

Best Practices

  1. Keep counts accurate: Ensure badge numbers reflect actual unread/pending items

  2. Clear when appropriate: Remove badges when counts reach zero

  3. Use reasonable numbers: Very large numbers may be truncated by the browser

  4. Sync with server: For multi-device users, sync badge counts across devices

  5. Update immediately: Update badges as soon as content changes, not on page reload

  6. Provide context: Combine app icon badges with in-app indicators

  7. Don't overuse: Reserve badges for truly important notifications

Badge vs Push Notifications

While badges and push notifications both alert users, they serve different purposes:

Feature
Badge
Push Notification

Visibility

Always visible on app icon

Temporary notification

Content

Number only

Rich text and images

User interaction

None required

Can be dismissed

Best for

Counts and totals

Time-sensitive alerts

Timing

Persistent until cleared

Appears once

Use both together for the best user experience: push notifications for new content, badges for ongoing counts.

Integration with Service Worker

Badges can be updated from the service worker, enabling background updates:

Complete Example: Messaging App

Troubleshooting

Badge not appearing

Possible causes:

  1. App not installed: Badges only work for installed PWAs

  2. Browser support: Check if the browser supports the Badging API

  3. Permissions: Some browsers require notification permissions for badges

Badge not updating

Common issues:

  1. Controller not found: Ensure the controller is properly initialized

  2. Invalid counter value: Must be a positive integer or 0

  3. Event not dispatched: Check that events are properly triggered

Badge count incorrect

Solutions:

  1. Sync with server: Fetch accurate count from server on app launch

  2. Persistent storage: Store count in localStorage for consistency

  3. Validate updates: Ensure all increment/decrement operations are correct

Platform-Specific Behavior

  • Chrome/Edge (Desktop): Badge appears as a circle with number

  • Chrome/Edge (Android): Badge shown as notification dot or number

  • Safari: Limited or no support (as of 2024)

  • Firefox: No support (as of 2024)

Always provide in-app indicators as a fallback for all users.

Last updated

Was this helpful?