How to communicate between multiple windows of same chrome apps

1.9k views Asked by At

I have a packaged chrome app having multiple windows. For example if I click a button in first window then a second window opened. Now how to send messages or commands to each other. I have read a lot about it but did not figure out as i am very much new to this. Any sample code will be very helpful.

There is a existing question How to communicate between multiple windows of the same chrome app?, but did not understand how to do it.

Thanks in advance!!!

2

There are 2 answers

0
Rivero On

You can use the postmessage method of a window, in order to send information to another window. By following this approach, you can execute a method from a window (A) on a different window (B). You'll need to create an event on window B that will inform A that the method ran correctly.

The code would be something like:

Sender:

//create popup window
var domain = 'http://scriptandstyle.com';
var myPopup = window.open(domain + '/windowPostMessageListener.html','myWindow');

//periodical message sender
setInterval(function(){
    var message = 'Hello!  The time is: ' + (new Date().getTime());
    console.log('blog.local:  sending message:  ' + message);
    myPopup.postMessage(message,domain); //send the message and target URI
},6000);

//listen to holla back
window.addEventListener('message',function(event) {
    if(event.origin !== 'http://scriptandstyle.com') return;
    console.log('received response:  ',event.data);
},false);

Destination:

//respond to events
window.addEventListener('message',function(event) {
    if(event.origin !== 'http://davidwalsh.name') return;
    console.log('message received:  ' + event.data,event);
    event.source.postMessage('holla back youngin!',event.origin);
},false);

You can also find an in-dept explanation here: http://davidwalsh.name/window-postmessage

0
saste On

In the case of a Chrome app, the part about the domain is not required.

You need something as:

targetWindow = chrome.app.window.get("window-id").contentWindow;
targetWindow.postMessage(message, "*");

to send a message, while to receive:

window.addEventListener('message', function(event) {
  var windowId = chrome.app.window.current().id;

  console.log(windowId + ': received a message: ' + event.data, event);
  var message = 'hello back!';
  console.log(windowId + ': sending message: ' + message);            
  event.source.postMessage(message, event.origin);
});