1.0.0 • Published 9 years ago

postmessage-client-server v1.0.0

Weekly downloads
6
License
-
Repository
github
Last release
9 years ago

npm version npm downloads

postmessage-client-server

A simple promise-based client and server to communicate between pages and iframes with postmessage.

All data passed will be serialized with JSON.

Installation

In your project dir:

npm install --save postmessage-client-server

Server

In your page the iframe will load on your server:

import {server} from 'postmessage-client-server';

server({
  // Include any methods you wish to call from the client
  bark(thing) {
    console.log('SERVER: Bark at', thing);
    return 'Barked at ' + thing;
  },
  sniff() {
    console.log('SERVER: Sniffing...');
    return ['grass', 'ball'];
  },
  beBad() {
    console.log('SERVER: About to misbehave...');
    throw 'Eating shoe';
  }
});

Client

On your client webpage:

import {client} from 'postmessage-client-server';

const urlToServerPage = 'http://mycorp.com/serverFrame.html';

client(urlToServerPage) // adds an iframe to the given url in your page
  .then(send => {
    // now we have our send function: send(method, args)
    send('sniff')
      .then(stuffSmelt => {
        console.log('CLIENT: We smelt:', stuffSmelt);
        stuffSmelt.forEach(item => {
          send('bark', item)
            .then(result => {
              console.log('CLIENT: Bark result:', result);
            });
        });
        send('beBad')
          .then(() => {
            console.log('CLIENT: Not punished');  // won't happen
          }, reason => {
            console.log('CLIENT: Got punished for', reason);
          });
      });
  });

Output

The console output from the above example would be:

SERVER: Sniffing...
CLIENT: We smelt: ["grass", "ball"]
SERVER: Bark at grass
SERVER: Bark at ball
SERVER: About to misbehave...
CLIENT: Got punished for Eating shoe
CLIENT: Bark result: Barked at grass
CLIENT: Bark result: Barked at ball 

Remember that the calls are asynchronous, so the order may vary.


Module submitted by Erik Rasmussen @erikras

1.0.0

9 years ago

0.0.11

10 years ago

0.0.10

10 years ago

0.0.9

10 years ago

0.0.8

10 years ago

0.0.7

10 years ago

0.0.6

10 years ago

0.0.5

10 years ago

0.0.4

10 years ago

0.0.3

10 years ago

0.0.2

10 years ago

0.0.1

10 years ago