Search code examples
javascriptbrowserwindowipchtml

Inter-Page communication in WWW?


Is there a way to make client-side interprocess communication between multiple web pages in javascript? Ideally I'd like to accomplish this without any complex server status updating, pinging, etc. and make it work solely on the client. If I could make this cross-browser as well, I would be in heaven haha. Any ideas? Thanks!


Solution

  • There are many ways of doing inter-window communication. They are Window.postMessage, Local Storage, WebRTC, and nowadays Shared Web Workers.

    Each of these has their own advantages/disadvantages:

    • Local Storage only works on same-origin pages (origin is protocol://website:port). It also broadcasts the message to every open window on the same origin, so it is slow if you have lots of pages open) Unfortunately this is the only cross-window tech supported on IE11 and below.
    • Shared Workers are only supported in Chrome and Firefox (and only supports same-origin as well, and the worker.js file must loaded from the same origin). You also have to 'relay' communication traffic from one page to another.
    • Window.postMessage only works between parent/child windows, but it supports cross-origin!

    Doing cross-origin communication between two independent websites is really clunky. You either have to perform a window.open() from the first website and use postMessage to communicate with the second website, or you have to set up this convoluted architecture, where you use hidden iframes on each site to talk to a web page hosted on the same website address, and these iframes then talk to each other through Local Storage or a Shared Worker. This is called a 'communication hub'. (Pretty complicated, right?)

    Worse still, inter-page communication has been seen as a security vulnerability and pretty much shunned. If some folks had their way, I imagine cross-origin postMessage would be removed. What I'd like to see is some protocol enhancements and some oAuth-like techniques created so we can secure the technique and make it reasonable. There's going to be a lot of data movement in the future to the client, and sharing it between web-pages will become critical.

    That said, don't re-make the wheel. There are several libraries out there that make inter-window communication possible.

    • Endpoint.js - A library (disclaimer) I developed which mediates communication between windows (on multiple origins), tabs, web workers, client/server, as well as IPC between processes. It also creates an ad-hoc overlay network that allows all of these techniques to relay information to each other.
    • crosstab - Implements the 'communication hub' approach above.
    • ozp-iwc - The IPC framework from OZone Widget Framework. Enables Local Storage and PostMessage