Skip to content

Seamless communication with iframes and other windows using proxies

Preet edited this page Jun 24, 2018 · 4 revisions

The Problem

Scripts on a web page are allowed to access a script on another window (e.g. an iframe or a popup/child window) only if they are in the same origin.

window.postMessage allows this cross-origin communication to happen.

To see how most people solve this problem, let's look at an example: A parent window wants to know something from the iframe, say, the user information.

  • Parent window loads and adds a message handler
  • iFrame loads and add a message handler
  • Parent window sends a message to iframe asking for userInfo
  • iFrame parses the message
  • iFrame sends a message to parent window.
  • Parent window parses the message
  • Parent window processes the userInfo

Helper functions

Developers will usually write some helper functions to deal with the boiler plate code. But, let's say you want to change the interface, or add new methods that you want to execute in the other window; you have to keep updating the code.

Proxies

What you really want, is to access the object in the other window as if it was in your own scope. For example, consider this object that is defined in the iframe:

{
  userInfo: {name: 'John Smith', age: 29},
  sendEmail(message) {
    // send email message
  }
}

If you create a Proxy

Clone this wiki locally