### Initialize and Test Postmonger Sessions
Source: https://github.com/kevinparkerson/postmonger/blob/master/dev/index.html
Demonstrates initializing multiple Postmonger sessions with different configurations and setting up event listeners. Use this to test inter-frame communication and event handling within the Postmonger framework.
```javascript
$(window).on('load', function(){ setTimeout(function(){ var connection1 = new Postmonger.Session({ connect: $('#iframe1') }); var connection2 = new Postmonger.Session({ connect: $('#iframe2')//, //from: 'http://localhost:8080' }); var connection3 = new Postmonger.Session({ connect: $('#iframe3')//, //to: 'http://loalhost:8080' }); var connection4 = new Postmonger.Session( { connect: $('#iframe1') }, { connect: $('#iframe2') }, { connect: $('#iframe3') } ); connection1.on('test1', function(message){ $('#console').append('
' + message + '
'); connection1.end(); }); connection2.on('test1', function(message){ $('#console').append('' + message + '
'); connection2.end(); }); connection3.on('test1', function(message){ $('#console').append('' + message + '
'); connection3.end(); }); connection4.on('test2', function(message){ $('#console').append('' + message + '
'); connection4.end(); }); connection1.trigger('test1', 'parent test1 received'); connection2.trigger('test1', 'parent test1 received'); connection3.trigger('test1', 'parent test1 received'); connection4.trigger('test2', 'parent test2 received'); }, 500); });
```
--------------------------------
### Low-Level Connection with Postmonger.Connection
Source: https://context7.com/kevinparkerson/postmonger/llms.txt
Create a low-level connection using `new Postmonger.Connection(options)` to represent a target window. It resolves targets from DOM elements, IDs, or `contentWindow` references. Returns `false` if a valid target cannot be resolved.
```javascript
// Connect by iframe element ID
var conn = new Postmonger.Connection({ connect: 'my-iframe-id' });
// Connect by raw DOM element
var iframe = document.getElementById('my-iframe');
var conn = new Postmonger.Connection({ connect: iframe });
// Connect with origin restrictions
var conn = new Postmonger.Connection({
connect: document.getElementById('secure-iframe').contentWindow,
from: 'https://secure-origin.example.com',
to: 'https://secure-origin.example.com'
});
if (!conn) {
console.error('Could not establish connection — target not found or lacks postMessage support.');
}
```
--------------------------------
### Module Loading and noConflict()
Source: https://context7.com/kevinparkerson/postmonger/llms.txt
Demonstrates how to load Postmonger using AMD, CommonJS, or as a browser global. Includes usage of the `noConflict()` method to avoid global namespace collisions.
```APIDOC
## Module loading — AMD, CommonJS, and browser global
Postmonger uses a UMD (Universal Module Definition) wrapper and works with AMD loaders (RequireJS), CommonJS environments (Node.js, Browserify, webpack), and as a plain browser global (`window.Postmonger`). A `noConflict()` method is provided for environments where the global name may clash.
```javascript
// AMD (RequireJS)
require(['postmonger'], function(Postmonger) {
var session = new Postmonger.Session({ connect: 'child-frame' });
session.trigger('init', { version: Postmonger.version });
});
// CommonJS / Node.js / Browserify / webpack
var Postmonger = require('postmonger');
var session = new Postmonger.Session({ connect: someIframeRef });
// Browser global (script tag)
//
var session = new Postmonger.Session({ connect: document.getElementById('app-frame') });
// noConflict — restore previous window.Postmonger and get the library reference
var PM = Postmonger.noConflict();
var session = new PM.Session({ connect: 'app-frame' });
// Check library version
console.log(Postmonger.version); // "0.0.14"
```
```
--------------------------------
### new Postmonger.Connection(options)
Source: https://context7.com/kevinparkerson/postmonger/llms.txt
Creates a low-level connection object for a target window. It resolves the target from various inputs like DOM elements or `contentWindow` references and can be configured with origin restrictions.
```APIDOC
## `new Postmonger.Connection(options)` — Low-level connection handle
Creates a low-level connection object representing a single target window. Resolves the target from a DOM element ID string, a raw DOM element, a jQuery object, or a `contentWindow` reference. Returns `false` if no valid `postMessage`-capable target can be resolved, printing a console warning. Primarily used internally by `Session`, but available for advanced custom use.
```javascript
// Connect by iframe element ID
var conn = new Postmonger.Connection({ connect: 'my-iframe-id' });
// Connect by raw DOM element
var iframe = document.getElementById('my-iframe');
var conn = new Postmonger.Connection({ connect: iframe });
// Connect with origin restrictions
var conn = new Postmonger.Connection({
connect: document.getElementById('secure-iframe').contentWindow,
from: 'https://secure-origin.example.com',
to: 'https://secure-origin.example.com'
});
if (!conn) {
console.error('Could not establish connection — target not found or lacks postMessage support.');
}
```
```
--------------------------------
### session.trigger(event, arg1, arg2, ...)
Source: https://context7.com/kevinparkerson/postmonger/llms.txt
Dispatches a named event and optional arguments to all connected windows. Arguments are automatically serialized to JSON.
```APIDOC
## session.trigger(event, arg1, arg2, ...)
### Description
Dispatches a named event and optional arguments to all connected windows via `postMessage`. Arguments are serialized to JSON automatically. The event name is stored under the `e` key, and positional arguments under `a1`, `a2`, etc. Any number of extra arguments can be passed. Triggers on the outgoing channel, causing all registered connections to receive the message.
### Parameters
- **event** (string) - Required - The name of the event to trigger.
- **arg1, arg2, ...** (any) - Optional - Any number of arguments to send with the event. These will be JSON-serialized.
### Request Example
```javascript
// Trigger with no payload
session.trigger('ready');
// Trigger with a single data argument
session.trigger('configLoaded', { theme: 'dark', lang: 'en' });
// Trigger with multiple arguments
session.trigger('userAction', 'click', { x: 120, y: 340 }, Date.now());
// Broadcast the same event to three iframes at once
var broadcast = new Postmonger.Session(
{ connect: $('#iframe1') },
{ connect: $('#iframe2') },
{ connect: $('#iframe3') }
);
broadcast.trigger('syncState', { count: 42 });
// All three iframes receive: { e: 'syncState', a1: { count: 42 } }
```
```
--------------------------------
### session.on(events, callback, context)
Source: https://context7.com/kevinparkerson/postmonger/llms.txt
Registers event listeners on the session to handle incoming messages. The callback is invoked with payload arguments when a matching `postMessage` is received.
```APIDOC
## session.on(events, callback, context)
### Description
Registers one or more event listeners on the session. The `events` parameter is a space-separated string of event names. When a matching `postMessage` arrives from a connected window, the callback is invoked with any payload arguments that were sent. The optional `context` argument sets the `this` value inside the callback. Multiple event names can be bound in a single call.
### Parameters
- **events** (string) - Required - A space-separated string of event names to listen for.
- **callback** (function) - Required - The function to execute when an event is received.
- **context** (object) - Optional - The `this` value for the callback function.
### Request Example
```javascript
// Listen for a single event with a payload argument
session.on('userLoggedIn', function(userData) {
console.log('User:', userData.name, userData.role);
});
// Listen for multiple events with one call
session.on('configLoaded tokenRefreshed', function(data) {
console.log('Event data received:', data);
});
// Listen with explicit context
var myComponent = {
name: 'Sidebar',
handleUpdate: function(payload) {
console.log(this.name, 'received update:', payload);
}
};
session.on('update', myComponent.handleUpdate, myComponent);
```
```
--------------------------------
### Standalone Event Emitter with Postmonger.Events
Source: https://context7.com/kevinparkerson/postmonger/llms.txt
Use `new Postmonger.Events()` for a standalone pub/sub emitter, independent of sessions. It exposes `on`, `off`, and `trigger` methods for internal messaging or custom communication layers.
```javascript
var emitter = new Postmonger.Events();
// Subscribe
emitter.on('notify', function(msg) {
console.log('Notification:', msg);
});
// Publish
emitter.trigger('notify', 'Hello from emitter!');
// Output: Notification: Hello from emitter!
// Unsubscribe all
emitter.off();
// Bind multiple space-separated events
emitter.on('start stop pause', function(info) {
console.log('Playback event:', info);
});
emitter.trigger('start', { track: 'song.mp3' });
// Output: Playback event: { track: 'song.mp3' }
```
--------------------------------
### Handle Postmonger Events in iframe
Source: https://github.com/kevinparkerson/postmonger/blob/master/dev/iframe3.html
Use this snippet to listen for 'test1' and 'test2' events from Postmonger.Session. It appends messages to a console and triggers a response. Ensure the Postmonger library is loaded.
```javascript
$(window).on('load', function(){ var connection = new Postmonger.Session(); connection.on('test1', function(message){ $('#console').append('' + message + '
'); connection.trigger('test1', 'iframe3 test1 received'); }); connection.on('test2', function(message){ $('#console').append('' + message + '
'); connection.trigger('test2', 'iframe3 test2 received'); }); });
```
--------------------------------
### Postmonger.Session Constructor
Source: https://context7.com/kevinparkerson/postmonger/llms.txt
Creates a new Postmonger session to manage cross-domain messaging connections. Options can specify target iframes, and origin restrictions for incoming and outgoing messages.
```APIDOC
## new Postmonger.Session(options, ...)
### Description
Creates a new session that manages one or more `postMessage` connections. Each options object specifies a target `connect` (iframe element, jQuery object, element ID string, or `contentWindow`) along with optional `from` (expected origin of incoming messages) and `to` (target origin for outgoing messages) restrictions. Multiple connection targets can be passed as separate arguments to broadcast to all of them at once. The returned session exposes `on`, `off`, `trigger`, and `end` methods.
### Parameters
#### Options Object
- **connect** (element | jQuery object | string | Window) - Required - The target iframe element, jQuery object, element ID string, or `contentWindow` to connect to.
- **from** (string) - Optional - The expected origin of incoming messages for strict origin enforcement.
- **to** (string) - Optional - The target origin for outgoing messages for strict origin enforcement.
### Request Example
```javascript
// Single iframe connection (by jQuery object)
var session = new Postmonger.Session({ connect: $('#my-iframe') });
// Single iframe connection (by element ID string)
var session = new Postmonger.Session({ connect: 'my-iframe' });
// Single iframe connection with strict origin enforcement
var session = new Postmonger.Session({
connect: document.getElementById('my-iframe').contentWindow,
from: 'https://trusted-child.example.com',
to: 'https://trusted-child.example.com'
});
// Multi-iframe broadcast session
var broadcast = new Postmonger.Session(
{ connect: $('#iframe1') },
{ connect: $('#iframe2') },
{ connect: $('#iframe3') }
);
// Child iframe connecting to parent window
var childSession = new Postmonger.Session();
```
```
--------------------------------
### Create Postmonger Session
Source: https://context7.com/kevinparkerson/postmonger/llms.txt
Instantiate a new Postmonger session. Options can specify the target iframe element, and optional origin restrictions for incoming and outgoing messages. Multiple connection targets can be provided for broadcast.
```javascript
// --- parent.html ---
// Single iframe connection (by jQuery object)
var session = new Postmonger.Session({ connect: $('#my-iframe') });
// Single iframe connection (by element ID string)
var session = new Postmonger.Session({ connect: 'my-iframe' });
// Single iframe connection with strict origin enforcement
var session = new Postmonger.Session({
connect: document.getElementById('my-iframe').contentWindow,
from: 'https://trusted-child.example.com', // only accept messages from this origin
to: 'https://trusted-child.example.com' // only send messages to this origin
});
// Multi-iframe broadcast session (sends to all three iframes simultaneously)
var broadcast = new Postmonger.Session(
{ connect: $('#iframe1') },
{ connect: $('#iframe2') },
{ connect: $('#iframe3') }
);
// --- child iframe (iframe1.html) ---
// No arguments = connects to parent window (window.parent)
var childSession = new Postmonger.Session();
```
--------------------------------
### Postmonger Module Loading
Source: https://context7.com/kevinparkerson/postmonger/llms.txt
Postmonger supports AMD, CommonJS, and browser global loading. Use `noConflict()` to avoid global namespace clashes and access the library reference.
```javascript
// AMD (RequireJS)
require(['postmonger'], function(Postmonger) {
var session = new Postmonger.Session({ connect: 'child-frame' });
session.trigger('init', { version: Postmonger.version });
});
// CommonJS / Node.js / Browserify / webpack
var Postmonger = require('postmonger');
var session = new Postmonger.Session({ connect: someIframeRef });
// Browser global (script tag)
//
var session = new Postmonger.Session({ connect: document.getElementById('app-frame') });
// noConflict — restore previous window.Postmonger and get the library reference
var PM = Postmonger.noConflict();
var session = new PM.Session({ connect: 'app-frame' });
// Check library version
console.log(Postmonger.version); // "0.0.14"
```
--------------------------------
### Handle Postmonger Events in Iframe
Source: https://github.com/kevinparkerson/postmonger/blob/master/dev/iframe2.html
This code sets up event listeners for 'test1' and 'test2' events from the Postmonger connection. It appends received messages to a console and triggers a response back to the main application.
```javascript
$(window).on('load', function(){ var connection = new Postmonger.Session(); connection.on('test1', function(message){ $('#console').append('' + message + '
'); connection.trigger('test1', 'iframe2 test1 received'); }); connection.on('test2', function(message){ $('#console').append(message); connection.trigger('test2', 'iframe2 test2 received'); }); });
```
--------------------------------
### new Postmonger.Events()
Source: https://context7.com/kevinparkerson/postmonger/llms.txt
Creates a standalone event emitter instance, independent of Postmonger sessions. It provides `on`, `off`, and `trigger` methods for managing custom application messaging.
```APIDOC
## `new Postmonger.Events()` — Standalone event emitter
A standalone pub/sub event emitter (ported from Backbone.Events) usable independently of sessions and connections. Exposes `on`, `off`, and `trigger` methods. Useful for internal application messaging or for building custom communication layers on top of Postmonger's event system.
```javascript
var emitter = new Postmonger.Events();
// Subscribe
emitter.on('notify', function(msg) {
console.log('Notification:', msg);
});
// Publish
emitter.trigger('notify', 'Hello from emitter!');
// Output: Notification: Hello from emitter!
// Unsubscribe all
emitter.off();
// Bind multiple space-separated events
emitter.on('start stop pause', function(info) {
console.log('Playback event:', info);
});
emitter.trigger('start', { track: 'song.mp3' });
// Output: Playback event: { track: 'song.mp3' }
```
```
--------------------------------
### Handle Postmonger Events in Iframe
Source: https://github.com/kevinparkerson/postmonger/blob/master/dev/iframe1.html
This code sets up event listeners for 'test1' and 'test2' events from Postmonger. It appends received messages to a console element and triggers a response back to Postmonger.
```javascript
$(window).on('load', function(){ var connection = new Postmonger.Session(); connection.on('test1', function(message){ $('#console').append('' + message + '
'); connection.trigger('test1', 'iframe1 test1 received'); }); connection.on('test2', function(message){ $('#console').append('' + message + '
'); connection.trigger('test2', 'iframe1 test2 received'); }); });
```
--------------------------------
### Send Postmonger Messages
Source: https://context7.com/kevinparkerson/postmonger/llms.txt
Dispatch named events and optional arguments to all connected windows. Arguments are automatically serialized to JSON. The event name is stored under 'e', and positional arguments under 'a1', 'a2', etc.
```javascript
// --- parent.html ---
var session = new Postmonger.Session({ connect: $('#child-iframe') });
// Trigger with no payload
session.trigger('ready');
// Trigger with a single data argument
session.trigger('configLoaded', { theme: 'dark', lang: 'en' });
// Trigger with multiple arguments
session.trigger('userAction', 'click', { x: 120, y: 340 }, Date.now());
// Broadcast the same event to three iframes at once
var broadcast = new Postmonger.Session(
{ connect: $('#iframe1') },
{ connect: $('#iframe2') },
{ connect: $('#iframe3') }
);
broadcast.trigger('syncState', { count: 42 });
// All three iframes receive: { e: 'syncState', a1: { count: 42 } }
```
--------------------------------
### Listen for Postmonger Events
Source: https://context7.com/kevinparkerson/postmonger/llms.txt
Register event listeners on a Postmonger session. Multiple event names can be bound in a single call. The optional context argument sets the 'this' value inside the callback.
```javascript
// --- child iframe ---
var session = new Postmonger.Session();
// Listen for a single event with a payload argument
session.on('userLoggedIn', function(userData) {
console.log('User:', userData.name, userData.role);
// Output: User: Alice admin
});
// Listen for multiple events with one call
session.on('configLoaded tokenRefreshed', function(data) {
console.log('Event data received:', data);
});
// Listen with explicit context
var myComponent = {
name: 'Sidebar',
handleUpdate: function(payload) {
console.log(this.name, 'received update:', payload);
}
};
session.on('update', myComponent.handleUpdate, myComponent);
// Output: Sidebar received update: { items: [...] }
```
--------------------------------
### CSS for Console Display
Source: https://github.com/kevinparkerson/postmonger/blob/master/dev/iframe2.html
Basic CSS styling for the console element used to display messages within the iframe.
```css
.console { border: 1px solid #f0b1b7; margin: 0 20px 20px; min-height: 80px; padding: 10px; }
```
--------------------------------
### session.off(events, callback, context)
Source: https://context7.com/kevinparkerson/postmonger/llms.txt
Removes previously registered event listeners from a Postmonger session. It can be used to remove all listeners, listeners for a specific event, or a single specific listener.
```APIDOC
## `session.off(events, callback, context)` — Remove event listeners
Removes previously registered event listeners. When called with no arguments, all listeners are removed. When called with just an event name, all listeners for that event are removed. When a specific callback and/or context is provided, only the matching listener is removed. Mirrors the `Backbone.Events` unbinding API.
```javascript
var session = new Postmonger.Session();
function onData(payload) {
console.log('received:', payload);
}
// Bind a listener
session.on('data', onData);
// Remove a specific listener by callback reference
session.off('data', onData);
// Remove all listeners for a specific event
session.off('update');
// Remove all listeners on the session entirely
session.off();
```
```
--------------------------------
### session.end()
Source: https://context7.com/kevinparkerson/postmonger/llms.txt
Tears down the Postmonger session by removing all event listeners and detaching the underlying window message event listener. This should be called when the session is no longer needed to prevent memory leaks.
```APIDOC
## `session.end()` — Tear down the session
Removes all incoming and outgoing event listeners and detaches the underlying `window` `message` event listener. Should be called when the session is no longer needed to prevent memory leaks and stale handlers, especially in single-page applications that mount and unmount components dynamically.
```javascript
// --- parent.html ---
var session = new Postmonger.Session({ connect: $('#child-iframe') });
session.on('taskComplete', function(result) {
console.log('Task finished:', result);
// Clean up after receiving the expected response
session.end();
console.log('Session ended, no further messages will be processed.');
});
session.trigger('startTask', { id: 'task-001', type: 'export' });
```
```
--------------------------------
### Remove Event Listeners with session.off()
Source: https://context7.com/kevinparkerson/postmonger/llms.txt
Use `session.off()` to remove event listeners. Call with no arguments to remove all listeners, with an event name to remove listeners for that event, or with a specific callback and context to remove a single listener. Mirrors Backbone.Events unbinding.
```javascript
var session = new Postmonger.Session();
function onData(payload) {
console.log('received:', payload);
}
// Bind a listener
session.on('data', onData);
// Remove a specific listener by callback reference
session.off('data', onData);
// Remove all listeners for a specific event
session.off('update');
// Remove all listeners on the session entirely
session.off();
```
--------------------------------
### Tear Down Session with session.end()
Source: https://context7.com/kevinparkerson/postmonger/llms.txt
Call `session.end()` to remove all event listeners and detach the `window.message` event listener. This is crucial for preventing memory leaks in dynamic applications.
```javascript
// --- parent.html ---
var session = new Postmonger.Session({ connect: $('#child-iframe') });
session.on('taskComplete', function(result) {
console.log('Task finished:', result);
// Clean up after receiving the expected response
session.end();
console.log('Session ended, no further messages will be processed.');
});
session.trigger('startTask', { id: 'task-001', type: 'export' });
```
=== COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.