How to communicate between multiple windows of the same chrome app?

亡梦爱人 提交于 2019-11-27 18:30:24

问题


When using chrome developer tools, it appears that each app window (and the background 'page') has its own javascript context (space of objects, thread of execution), and yet the createdWindow callback of chrome.app.window.create apparently provides direct access to the objects of the 'other' window that was just created.

Given that, I'm unclear on the best way to communicate between windows; e.g. if I open a second window to act as a dialog box, when the user clicks OK to save changes, should I be using postMessage, sendMessage, or just call a function on an object in the main window. I've looked at the messaging samples, and they seem focused on communication between two different apps, or between an app and an extension.

So, I'm seeking a clear description of the memory and execution model within one app. Are there really separate contexts, or is it just one space of objects, with one thread of execution? What is the best way to communicate between windows of the same chrome app?


回答1:


That is a great question James!

Multiple chrome windows are not completely separate. They share a single thread and object space, however the window object is different for each. In javascript unscoped references to things are looked up on the current window, so this makes the windows appear to be different object spaces - but they are not really.

So, you can reach into another window and execute a function there, or manipulate state in other ways (e.g. set a variable on another window to a function from the current window) and it is acceptable and supported.




回答2:


You might find the chrome.app.window.getAll() and chrome.app.window.get() methods useful. They are however new to Chrome 33 which is not yet in the stable channel.

As an alternative you could hold an array of opened AppWindow objects in the background page context.

You can then get a reference to the background page context from any window using the chrome.runtime.getBackgroundPage() method



来源:https://stackoverflow.com/questions/20765870/how-to-communicate-between-multiple-windows-of-the-same-chrome-app

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!