import {Meta} from '@storybook/addon-docs/blocks'

<Meta title='@dxtmisha/en/functional-basic/Classes/BroadcastMessage - BroadcastChannel Messaging'/>

# BroadcastMessage Class

A class for handling messaging between different browser contexts (tabs, windows, iframes) using the `BroadcastChannel` API. It provides a convenient interface for sending and receiving data with automatic channel lifecycle management and error handling.

Features automatic prefix naming to prevent conflicts and integrates with `ErrorCenter` for monitoring initialization failures.

## Key Features

- **Cross-Context Communication** — simple data synchronization between all windows of the same origin.
- **Callback-Based** — automatic processing of incoming messages and errors through registered callback functions.
- **Runtime Safety** — built-in DOM environment checking prevents errors during Server-Side Rendering (SSR).
- **Channel Isolation** — automatic unique prefixing for channel names via `DataStorage`.
- **Strong Typing** — full TypeScript generics support to ensure message data integrity.

## Initialization

To initialize the object, call the constructor `BroadcastMessage(name, callback, callbackError, errorCenter)`.

### Generic Constraints

- `Message = any` — the type of the message payload.

**Parameters:**
- `name: string` — unique channel name.
- `callback?: (event: MessageEvent<Message>) => void` — callback function executed when a message is received.
- `callbackError?: (event: MessageEvent<Message>) => void` — callback function executed when a message error occurs.
- `errorCenter: ErrorCenterInstance` — error center instance (defaults to: `ErrorCenter.getItem()`).

```typescript
import { BroadcastMessage } from '@dxtmisha/functional-basic'

const messenger = new BroadcastMessage<string>(
  'my-channel',
  (event) => console.log('Received:', event.data)
)
```

## Methods

### Action

- `post(message: Message): this` — Sends a message to all listeners in the same channel.
- `destroy(): this` — Closes the channel and stops listening for messages.

### Configuration and Access

- `getChannel(): BroadcastChannel | undefined` — Returns the underlying `BroadcastChannel` instance.
- `setCallback(callback: Function): this` — Updates the function for processing incoming messages.
- `setCallbackError(callbackError: Function): this` — Updates the function for processing message errors.

## Examples

### Syncing State Between Tabs

```typescript
import { BroadcastMessage } from '@dxtmisha/functional'

// In all application tabs
const authChannel = new BroadcastMessage<string>('auth-status', (event) => {
  if (event.data === 'LOGOUT') {
    authModule.clearSession()
    window.location.reload()
  }
})

// When a user logs out in one of the tabs
function onLogout() {
  authChannel.post('LOGOUT')
}
```

### Updating Data Handler on the Fly

```typescript
const messenger = new BroadcastMessage('data-sync')

messenger.setCallback((event) => {
  console.log('New data received:', event.data)
})

messenger.post({ id: 1, status: 'active' })
```
