npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2024 – Pkg Stats / Ryan Hefner

postmessage-promise

v3.2.1

Published

postmessage-promise is a client-server like, WebSocket like, full Promise syntax supported postMessage library. 一个类 client-server 模式、类 WebSocket like 模式、全 Promise 语法支持的 postMessage 库

Downloads

173

Readme

postmessage-promise

postmessage-promise is a client-server like, WebSocket like, full Promise syntax supported postMessage library.

中文文档

Why need this

  • Sometimes, the server page's logic unit is not ready when Document is loaded, so we need a function to start a listening when logic unit is ready.
  • Sometimes, we need waiting for the postMessage's response before post next message.

Features

  • postMessage().then() syntax & ES6 async/await syntax supported.
  • target window: frame.contentWindow / openedWindow / window.parent / window.opener.
  • client-server like, and WebSocket like.
  • 3-Way Handshake at connecting.
  • client use callServer to connect with server unless timeout. You can use the same serverObject to create more server-caller if necessary. (the server may be a frame.contentWindow、a new opened window、window.parent or window.opener)
  • server use startListening to start a server listening, each server listening can only connect with one client. You can start more than one listening if necessary.

connecting

message-channel

How to use it

$ npm i postmessage-promise --save

use with script tag

<script type="text/javascript" src="https://unpkg.com/[email protected]/build/postmessage-promise.umd.js"></script>
<script>
  const { startListening, callServer, utils } = postMessagePromise;
</script>

start

  • client call to server
import { callServer, utils } from "postmessage-promise";
const serverObject = { 
  server: frame.contentWindow, // openedWindow / window.parent / window.opener; 
  origin: "*", // target-window's origin or *
};
const options = {}; 
callServer(serverObject, options).then(e => {
  const { postMessage, listenMessage, destroy } = e;
  listenMessage((method, payload, response) => {
    response("Petter's response.");
  });
  postMessage("hello", "I am Petter.").then(res => {
    postMessage("...");
  });
});
  • server start listening
import { startListening } from "postmessage-promise";
const options = {};
startListening(options).then(e => {
  const { postMessage, listenMessage, destroy } = e;
  listenMessage((method, payload, response) => {
    response("Alice's response.");
  });
  postMessage('hello', "I am Alice.").then(res => {
    postMessage("...");
  });
});

serverObject

server is the target window object that you want post message to. And the origin is the target-window's origin, you can set '*' in Cross-origin case.

  {
    server: frame.contentWindow, // openedWindow / window.parent / window.opener
    origin
  };

options

const options = { 
  eventFilter: (event) => true, 
  timeout: 20 * 1000,
  onDestroy: () => { if (frame) { frame.parentNode.removeChild(frame); } }
}
  • 'eventFilter' is a filter for post messages event.
  • 'timeout' is set for client to connect with server, or for client and server's response of postMessage.then.

Demo

client (iframe case)

import { callServer, utils } from "postmessage-promise";
const { getOpenedServer, getIframeServer } = utils;
const iframeRoot = document.getElementById("iframe-root");
const serverObject = getIframeServer(iframeRoot, "/targetUrl", "iname", ['iframe-style']);
const options = {}; 
callServer(serverObject, options).then(e => {
  console.log("connected with server");
  const { postMessage, listenMessage, destroy } = e;
  // post message to server and wait for response
  const method = "testPost";
  const payload = "this is client post payload";
  postMessage(method, payload).then(e => {
    console.log("response from server: ", e);
  });
  // listener for server message
  listenMessage((method, payload, response) => {
    console.log("client received: ", method, payload);
    const time = new Date().getTime();
    setTimeout(() => {
      // response to server
      response({
        time,
        msg: "this is a client response"
      });
    }, 200);
  });
});

client (window.open case)

import { callServer, utils } from "postmessage-promise";
const { getOpenedServer, getIframeServer } = utils;
const serverObject = getOpenedServer("/targetUrl");
const options = {}; 
callServer(serverObject, options).then(e => {
  console.log("connected with server");
  const { postMessage, listenMessage, destroy } = e;
  // post message to server and wait for response
  const method = "testPost";
  const payload = "this is client post payload";
  postMessage(method, payload).then(e => {
    console.log("response from server: ", e);
  });
  // listener for server message
  listenMessage((method, payload, response) => {
    console.log("client received: ", method, payload);
    const time = new Date().getTime();
    setTimeout(() => {
      // response to server
      response({
        time,
        msg: "this is a client response"
      });
    }, 200);
  });
});

server

import { startListening } from "postmessage-promise";
const options = {};
startListening(options).then(e => {
  console.log("connected with client");
  const { postMessage, listenMessage, destroy } = e;
  // listener for client message
  listenMessage((method, payload, response) => {
    console.log("server received: ", method, payload);
    const time = new Date().getTime();
    setTimeout(() => {
      // response to client
      response({
        time,
        msg: "this is a server response"
      });
    }, 200);
  });
  // post message to client and wait for response
  const method = "toClient";
  const payload = { msg: 'this is server post payload' };
  postMessage(method, payload).then(e => {
    console.log("response from client: ", e);
  });
});

multiple server and client

// server:
const listener = (handler, name)=>{
  startListening({
    serverInfo: {
      name: "thisIsServer"+name
    }
  }).then(e=>{
    listener(handler, Math.random());
    handler(e);
  });
}
listener((e)=>{}, 'name1');
//
// client:
callServer(serverObject, {
  onDestroy: () => { }, clientInfo: { name: "thisIsClient"+ Math.random() }
}).then(e => {})