# postmates-js

> A powerful, simple, promise-based postMessage library

Latest version **0.0.3** (published 2021-11-17) · MIT license · 0 weekly downloads

## Install

```sh
npm install postmates-js
pnpm add postmates-js
yarn add postmates-js
bun add postmates-js
```

## Health

**Score 20/100 (F)** — status: abandoned.

Positive: esm support; no vulnerabilities.

Warnings: low downloads; no types; pre 1.0.

Negative: abandoned; low maintenance score.

## Facts

| | |
|---|---|
| Version | 0.0.3 |
| Published | 2021-11-17 |
| First published | 2021-11-15 |
| Weekly downloads | 0 |
| License | MIT |
| TypeScript types | none |
| Module format | ESM + CommonJS |
| Dependencies | 0 |
| Unpacked size | 80.9 KB |
| Known vulnerabilities | 0 |
| Install scripts | no |
| Author | Jacob Kelley |
| Maintainers | zousanjun |
| Keywords | postMessage, secure, handshake, promise, iframes, pci, security |

## Links

- npm: https://www.npmjs.com/package/postmates-js
- Repository: https://gitee.com/videring/postmates-js
- Issues: https://gitee.com/videring/postmates-js/issues
- npm.io page: https://npm.io/package/postmates-js

## Alternatives

- [@commercetools/sync-actions](https://npm.io/package/@commercetools/sync-actions.md) — 25.1K weekly downloads
- [cwait](https://npm.io/package/cwait.md) — 21.4K weekly downloads
- [@ledgerhq/hw-app-cosmos](https://npm.io/package/@ledgerhq/hw-app-cosmos.md) — 4.2K weekly downloads
- [@financial-times/o-loading](https://npm.io/package/@financial-times/o-loading.md) — 2.8K weekly downloads
- [fa](https://npm.io/package/fa.md) — 185 weekly downloads

## Recent versions

- 0.0.3 (latest) — 2021-11-17
- 0.0.2 — 2021-11-16
- 0.0.1 — 2021-11-15
- 0.0.0 — 2021-11-15

## README

> A powerful, simple, promise-based `postMessage` iFrame communication library.

## PostmatesJS, based on [postmate@1.5.2](https://www.npmjs.com/package/postmate), adds the following:
- support iframe dom
- support communicating with at least one iframe
- support communicating with `window.open`


_PostmatesJS_ is a promise-based API built on `postMessage`. It allows a parent page to speak with a child `iFrame` across origins with minimal effort.

You can download the compiled javascript directly [here](/build/postmates-js.min.js)

* [Features](#features)
* [Installing](#installing)
* [Glossary](#glossary)
* [Usage](#usage)
* [API](#api)
* [Troubleshooting/FAQ](#troubleshootingfaq)
* [License](#license)

***

## Features

* Promise-based API for elegant and simple communication.
* Secure two-way parent <-> children handshake, with message validation.
* Child expose a retrievable `model` object that the parent can access.
* Child emit events that the parent can listen to.
* Parent can `call` functions within a `child`
* *Zero* dependencies. Provide your own polyfill or abstraction for the `Promise` API if needed.
* Lightweight, weighing in at ~ <span class="size">`1.9kb`</span> (minified & gzipped).

NOTE: While the underlying mechanism is [window.postMessage()](https://developer.mozilla.org/en-US/docs/Web/API/Window/postMessage), only iFrame is supported.

## Installing
PostmatesJS can be installed via NPM.

**NPM**
```bash
$ yarn add postmates-js # Install via Yarn
```

```bash
$ npm i postmates-js --save # Install via NPM
```

## Glossary
* **`Parent`**: The **top level** page that will embed an `iFrame`, creating a `Child`.
* **`Children`**: The **bottom level** page loaded within the `iFrame` or new tab page by `window.open`.
* **`Model`**: The object that the `Child` exposes to the `Parent`.
* **`Handshake`**: The process by which the parent frame identifies itself to the child, and vice versa. When a handshake is complete, the two contexts have bound their event listeners and identified one another.

## Usage
1. The `Parent` begins communication with the `Child`. A handshake is sent, the `Child` responds with a handshake reply, finishing `Parent`/`Child` initialization. The two are bound and ready to communicate securely.

2. The `Parent` fetches values from the `Child` by property name. The `Child` can emit messages to the parent. The `Parent` can `call` functions in the `Child` `Model`.

***
### Example

**parent.com**
```html
<body>
	<div>Parent Page/div>
	<iframe id='cid1' style="width: 300px; height: 300px;" src="http://localhost:8081/c1.html"></iframe>
	<div id='cid2' style="width: 300px; height: 300px;"></div>
</body>
```
```javascript
// Kick off the handshake with the iFrame
PostmatesJS.debug = true;
const open = window.open('http://localhost:8083/c3.html', '_blank')
const handshake = new PostmatesJS([
    {
        container: document.getElementById("cid1"), // first way
        url: "",
        name: "name1"
    }, {
        container: document.getElementById("cid2"), // second way, similar to `postmate`
        url: "http://localhost:8082/c2.html",
        name: "name2"
    }, {
        container: open, // document.getElementById("cid2"), // third way, open a new page with `window.open` 
        url: "http://localhost:8083/c3.html",
        name: "name2"
    }
]);

// When parent <-> child handshake is complete, data may be requested from the child
handshake.then(parentAPIs => {
    parentAPIs.forEach(parentAPI => {
        parentAPI.on('some-event', data => {
            console.log(data)
        }); // Logs "Hello, World!"
        parentAPI.call("demoFunction", {options:"Hello, PostmatesJS!"})
    })
});
```

**localhost:8081/c1.html**
```javascript
PostmatesJS.debug = true
const model = new PostmatesJS.Model({
    demoFunction:(options) =>{
        console.log('child1', options)
    }
 });
model.then(childAPI => {
    childAPI.emit('some-event', 'Hello, World! Child1');
});
```
**localhost:8082/c2.html**
```javascript
PostmatesJS.debug = true
const model = new PostmatesJS.Model({
    //demoFunction：提供给父页面的方法
    //options: 从父页面传入的参数信息
    demoFunction:(options) =>{
        console.log('child2', options)
    }
});
model.then(childAPI => {
    childAPI.emit('some-event', 'Hello, World! Child2');
});
```
**localhost:8083/c3.html**
```javascript
PostmatesJS.debug = true
const model = new PostmatesJS.Model({
    //demoFunction：提供给父页面的方法
    //options: 从父页面传入的参数信息
    demoFunction:(options) =>{
        console.log('child3', options)
    }
});
model.then(childAPI => {
    childAPI.emit('some-event', 'Hello, World! Child3');
});
```

***

## API

> ## `PostmatesJS.debug`

```javascript
// parent.com or child.com
PostmatesJS.debug = true;
new PostmatesJS(options);
```

| Name | Type | Description | Default |
| --- | --- | --- | --- |
| `debug` | `Boolean` | _Set to `true` to enable logging of additional information_ | `false` |

---

> ## `PostmatesJS.Promise`

```javascript
// parent.com or child.com
PostmatesJS.Promise = RSVP.Promise;
new PostmatesJS(options);
```

| Name | Type | Description | Default |
| --- | --- | --- | --- |
| `Promise` | `Object` | _Replace the Promise API that PostmatesJS uses_ | `window.Promise` |

---

> ## `PostmatesJS(options)`

```javascript
// parent.com
new PostmatesJS({
  container: document.body,
  url: 'http://child.com/',
  classListArray: ["myClass"],
  model: { foo: 'bar' }
});
```

> This is written in the parent page.  Creates an iFrame at the specified `url`. Initiates a connection with the child. Returns a Promise that signals when the handshake is complete and communication is ready to begin.

**Returns**: Promise(child)

#### Properties

| Name | Type | Description | Default |
| --- | --- | --- | --- |
| **`container`** (optional) | `DOM Node Element` | _An element to append the iFrame to_ | `document.body`
**`url`** | `String` | _A URL to load in the iFrame. The origin of this URL will also be used for securing message transport_ | none |
**`classListArray`** | `Array` | _An Array to add classes to the iFrame. Useful for styling_ | none |
**`model`** | `Object` | _An object literal to represent the default values of the Childs model_ | none |

---

> ## `PostmatesJS.Model(model)`

```javascript
// child.com
new PostmatesJS.Model({
  // Serializable values
  foo: "bar",
  // Functions
  height: () => document.height || document.body.offsetHeight,
  // Promises
  data: fetch(new Request('data.json'))
});
```

> This is written in the child page. Calling `PostmatesJS.Model` initiates a handshake request listener from the `Child`. Once the handshake is complete, an event listener is bound to receive requests from the `Parent`. The `Child` model is _extended_ from the `model` provided by the `Parent`.

**Returns**: Promise(handshakeMeta)

#### Parameters

| Name | Type | Description | Default |
| --- | --- | --- | --- |
| **`model`** | `Object` | _An object of gettable properties to expose to the parent. Value types may be anything accepted in `postMessage`. Promises may also be set as values or returned from functions._ | `{}` |

---

> ## `child.get(key)`

```javascript
// parent.com
new PostmatesJS({
  container: document.body,
  url: 'http://child.com/'
}).then(child => {
  child.get('something').then(value => console.log(value));
});
```

> Retrieves a value by property name from the `Childs` `model` object.

**Returns**: Promise(value)

#### Parameters

| Name | Type | Description |
| --- | --- | --- |
| **`key`** | `String` (required) | _The string property to lookup in the childs `model`_ |

---

> ## `child.call(key, data)`

```javascript
// parent.com
new PostmatesJS({
  container: document.body,
  url: 'http://child.com/'
}).then(child => {
  child.call('sayHi', 'Hello, World!');
});
```

> Calls the function `sayHi` in the `Child` `Model` with the parameter `Hello, World!`

**Returns**: `undefined`

#### Parameters

| Name | Type | Description |
| --- | --- | --- |
| **`key`** | `String` (required) | _The string property to lookup in the childs `model`_ |
| **`data`** | `Mixed` | _The optional data to send to the child function_ |

---

> ## `child.destroy()`

```javascript
// parent.com
new PostmatesJS({
  container: document.body,
  url: 'http://child.com/'
}).then(child => child.destroy());
```

> Removes the `iFrame` element and destroys any `message` event listeners; if the child is opened with `window.open`, then Closes the open page.

**Returns**: `undefined`

---

> ## `child`

```javascript
new PostmatesJS(options).then(child => {
  child.get('height')
    .then(height => child.frame.style.height = `${height}px`);
});
```

> The iFrame Element that the parent is communicating with

## Troubleshooting/FAQ

### General
#### Why use Promises for an evented API?
> _Promises provide a clear API for fetching data. Using an evented approach often starts backwards. if the parent wants to know the childs height, the child would need to alert the parent, whereas with PostmatesJS, the Parent will request that information from the child in a synchronous-like manner. The child can emit events to the parent as well, for those other use-cases that still need to be handled._

### Silent Parent/Child
#### I've enabled logging but the parent or child is not logging everything.
> _Postmate.debug needs to be set in both the parent and child for each of them to log their respective information_

#### The child does not respond to communication from the Parent
> _Make sure that you have initialized PostmatesJS.Model in your child page._

### Restrictive Communication
#### I want to retrieve information from the parent by the child
> _Postmate (by design) is restrictive in its modes of communication. This enforces a simplistic approach: The parent is responsible for logic contained within the parent, and the child is responsible for logic contained within the child. If you need to retrieve information from parent -> child, consider setting a default `model` in the parent that the child may extend._

#### I want to send messages to the child from the parent
> _This is specifically what the `call` function is for._

### Security
#### What is the Handshake and why do I need one?
> _By default, all `message` events received by any (parent) page can come from any (child) location. This means that the `Parent` must always enforce security within its message event, ensuring that the `child` (origin) is who we expect them to be, that the message is a response from an original request, and that our message is valid. The handshake routine solves this by saving the identities of the child and parent and ensuring that no changes are made to either._

#### How are messages validated?
> _The origin of the request, the message type, the postMessage mime-type, and in some cases the message response, are all verified against the original data made when the handshake was completed._

## License
MIT

---
_Source: https://npm.io/package/postmates-js · Machine-readable twin of the npm.io package page. Health data is recomputed on every publish._
