Frame Messenger
A tiny JavaScript class to simplify communication between different browser frames, supporting both promises and callbacks.
Installation
npm install frame-messenger
Documentation
new FrameMessenger(options)
var messenger = frame: window targetFrame: windowparent name: 'iframe' targetName: 'topFrame' Promise: windowPromise // optional;
Options
frame
{Window} required
Frame should be a reference to the current window (i.e., window
)
name
{String} required
An arbriary name to assign to the current frame. Other frames must use this name when initiating communication.
targetFrame
{Window} required
A reference to the frame we will be communicating with (e.g., parent
, top
, opener
, iframeEl.contentWindow
)
targetName
{Window} required
An arbriary name to assign to the other frame we want to communicate with. The other frame must use this same name to reference itself (see examples below).
Promise
{Promise constructor} optional
A promise constructor to use for creating promises. When not passed, regular node-style callbacks will be used.
messenger.postMessage()
Send a message to the other frame:
var messenger = frame: window targetFrame: parent name: 'iframe' targetName: 'topFrame'; messenger;
Pass in a callback to process the response from the other frame:
messenger;
Alternately, postMessage
will return a promise if FrameMessenger
was invoked with a Promise
property:
var messenger = frame: window targetFrame: windowparent name: 'iframe' targetName: 'topFrame' Promise: RSVPPromise // choose your favorite promise library; messenger;
You can maintain an open communication with the other frame by utilizing the callback
argument that is passed to the postMessage
callback:
messenger;
messenger.onMessage(data, callback)
Handle messages from the other frame with onMessage
:
messenger;
The other frame can send a response back by utilizing the callback argument passed to onMessage
:
messenger;
See the tests for other examples.
Tests
Running the tests:
npm installnpm test
License
This project is distributed under the MIT license.