项目作者: krakenjs

项目描述 :
Cross domain post-messaging on the client side using a simple listener/client pattern.
高级语言: JavaScript
项目地址: git://github.com/krakenjs/post-robot.git
创建时间: 2016-05-27T17:05:49Z
项目社区:https://github.com/krakenjs/post-robot

开源协议:Other

下载


post-robot [:]-\-<

build status
code coverage
npm version

Cross domain post-messaging on the client side, using a simple listener/client pattern.

Send a message to another window, and:

Serialization

post-robot will serialize and deserialize the following data types in messages:

  • Objects, arrays, strings, numbers, booleans, null
    • Note: this includes any JSON-serializable types
  • Functions
  • Promises
    • Note: deserialized promises will be instances of ZalgoPromise
  • Error objects
    • e.g. new Error("This error will self-destruct in 10, 9, 8...")
  • Regex objects
    • e.g. /[a-zA-Z0-9]*/

Simple listener and sender

  1. // Set up a listener
  2. postRobot.on("getUser", function (event) {
  3. // Have it return some data to the calling window
  4. return {
  5. id: 1234,
  6. name: "Zippy the Pinhead",
  7. // Yep, we're even returning a function to the other window!
  8. logout: function () {
  9. return $currentUser.logout();
  10. },
  11. };
  12. });
  1. // Call the listener, on a different window, on a different domain
  2. postRobot
  3. .send(someWindow, "getUser", { id: 1337 })
  4. .then(function (event) {
  5. var user = event.data;
  6. console.log(event.source, event.origin, "Got user:", user);
  7. // Call the user.logout function from the other window!
  8. user.logout();
  9. })
  10. .catch(function (err) {
  11. // Handle any errors that stopped our call from going through
  12. console.error(err);
  13. });

Listener with promise response

  1. postRobot.on("getUser", function (event) {
  2. return getUser(event.data.id).then(function (user) {
  3. return {
  4. name: user.name,
  5. };
  6. });
  7. });

One-off listener

  1. postRobot.once("getUser", function (event) {
  2. return {
  3. name: "Noggin the Nog",
  4. };
  5. });

Cancelling a listener

  1. var listener = postRobot.on("getUser", function (event) {
  2. return {
  3. id: event.data.id,
  4. name: "Zippy the Pinhead",
  5. };
  6. });
  7. listener.cancel();

Listen for messages from a specific window

  1. postRobot.on("getUser", { window: window.parent }, function (event) {
  2. return {
  3. name: "Guybrush Threepwood",
  4. };
  5. });

Listen for messages from a specific domain

  1. postRobot.on("getUser", { domain: "http://zombo.com" }, function (event) {
  2. return {
  3. name: "Manny Calavera",
  4. };
  5. });

Set a timeout for a response

  1. postRobot
  2. .send(someWindow, "getUser", { id: 1337 }, { timeout: 5000 })
  3. .then(function (event) {
  4. console.log(event.source, event.origin, "Got user:", event.data.name);
  5. })
  6. .catch(function (err) {
  7. console.error(err);
  8. });

Send a message to a specific domain

  1. postRobot
  2. .send(someWindow, "getUser", { id: 1337 }, { domain: "http://zombo.com" })
  3. .then(function (event) {
  4. console.log(event.source, event.origin, "Got user:", event.data.name);
  5. });

Async / Await

  1. postRobot.on("getUser", async ({ source, origin, data }) => {
  2. let user = await getUser(data.id);
  3. return {
  4. id: data.id,
  5. name: user.name,
  6. };
  7. });
  1. try {
  2. let { source, origin, data } = await postRobot.send(someWindow, `getUser`, {
  3. id: 1337,
  4. });
  5. console.log(source, origin, "Got user:", data.name);
  6. } catch (err) {
  7. console.error(err);
  8. }

Secure Message Channel

For security reasons, it is recommended that you always explicitly specify the window and domain you want to listen
to and send messages to. This creates a secure message channel that only works between two windows on the specified domain:

  1. postRobot.on(
  2. "getUser",
  3. { window: childWindow, domain: "http://zombo.com" },
  4. function (event) {
  5. return {
  6. id: event.data.id,
  7. name: "Frodo",
  8. };
  9. }
  10. );
  1. postRobot
  2. .send(someWindow, "getUser", { id: 1337 }, { domain: "http://zombo.com" })
  3. .then(function (event) {
  4. console.log(event.source, event.origin, "Got user:", event.data.name);
  5. })
  6. .catch(function (err) {
  7. console.error(err);
  8. });

Functions

Post robot lets you send across functions in your data payload, fairly seamlessly.

For example:

  1. postRobot.on("getUser", function (event) {
  2. return {
  3. id: event.data.id,
  4. name: "Nogbad the Bad",
  5. logout: function () {
  6. currentUser.logout();
  7. },
  8. };
  9. });
  1. postRobot.send(myWindow, "getUser", { id: 1337 }).then(function (event) {
  2. var user = event.data;
  3. user.logout().then(function () {
  4. console.log("User was logged out");
  5. });
  6. });

The function user.logout() will be called on the original window. Post Robot transparently messages back to the
original window, calls the function that was passed, then messages back with the result of the function.

Because this uses post-messaging behind the scenes and is therefore always async, user.logout() will always return a promise, and must be .then‘d or awaited.

Parent to popup messaging

Unfortunately, IE blocks direct post messaging between a parent window and a popup, on different domains.

In order to use post-robot in IE9+ with popup windows, you will need to set up an invisible ‘bridge’ iframe on your parent page:

  1. [ Parent page ]
  2. +---------------------+ [ Popup ]
  3. | xx.com |
  4. | | +--------------+
  5. | +---------------+ | | yy.com |
  6. | | [iframe] | | | |
  7. | | | | | |
  8. | | yy.com/bridge | | | |
  9. | | | | | |
  10. | | | | | |
  11. | | | | | |
  12. | | | | +--------------+
  13. | +---------------+ |
  14. | |
  15. +---------------------+

a. Use the special ie build of post-robot: dist/post-robot.ie.js.

b. Create a bridge path on the domain of your popup, for example http://yy.com/bridge.html, and include post-robot:

  1. <script src="http://yy.com/js/post-robot.ie.js"></script>

c. In the parent page on xx.com which opens the popup, include the following javascript:

  1. <script>
  2. postRobot.bridge.openBridge("http://yy.com/bridge.html");
  3. </script>

Now xx.com and yy.com can communicate freely using post-robot, in IE.