JavaScript Cross Tab Cross Site Communication

Subscribe to my newsletter and never miss my upcoming articles

Hello, everyone 👋

In this article you will read about how to enable data transfer between browser tabs, across two different sites using JavaScript.

In JavaScript we can use to open a window or browser tab. It returns a reference object of the window we opened, using which we will be able to control the opened window like closing, check if it is closed by the user, send data etc.

/* open a browser tab of site */
const windowObj ='');


Using window.postMessage we can send data across windows or browser tabs. This is how you do it,

const url = '';
const windowObj =;
/* send data to an opened browser tab of site */
windowObj.postMessage('hello world', url);


Use window.onmessage event on the opened window to listen and receive the message that was sent,

/* Receiver Window - */
window.onmessage = (event) => {
    /* received data: hello world */
    /* send response back to sender */
    event.source.postMessage('message received!', event.origin);

/* Sender Window - */
window.onmessage = (event) => {
   /* received data: message received! */

Determine if the opened window is ready to receive data

For the opened window to receive data it should have javascript fully loaded and onmessage event is subscribed, else the data sent will be lost. So how can the sender window determine that the receiver window is loaded and ready to receive data before sending any data?

If the domain name of sender and receiver window URL is the same, receiver can use window.opener object to send handshaking message to notify sender when loaded and ready. window.opener is the reference object of the sender window that opened the receiver window.

/* Receiver window starts the communication with sender */
window.opener.postMessage('I am ready!', window.opener);

If the sender and receiver window URL domain name is different (cross-site) above method will not work and give you cross-origin error due to security reasons.

cross origin error.PNG

To get around the cross-origin issue, we need to continuously poll the receiver window and see if it is loaded and ready to receive data. We can do as given below,

/* Sender - */
const url = '';
const windowObj =;
/* start polling receiver for every 100ms to see if it is loaded and ready */
const poll = setInterval(() => windowObj.postMessage('are you ready?', url), 100);

window.onmessage = (event) => {
   /* check if response received from receiver */
   if( === 'I am ready!') { 
   /* stop polling */
   /* send actual data */
   windowObj.postMessage('here is your data', url); 

/* Receiver -*/
window.onmessage = (event) => {
  /* make sure message received from trusted source */
  if(event.origin === '') { 
     if ( === 'are you ready?') {
         event.source.postMessage('I am ready!', event.origin);
     } else {
         /* process actual data */

Thanks for reading! Stay tuned 🙂