简体   繁体   English

如何在两个浏览器窗口之间进行通信?

[英]How to Communicate between two browser windows?

I have parent browser window P . 我有父浏览器窗口P. on clicking a button a new browser window WIN-A is opened. 单击按钮时,将打开一个新的浏览器窗口WIN-A。 then again pressing the same button it should read the title of the WIN-A window and open WIN-B 然后再次按下相同的按钮,它应该读取WIN-A窗口的标题并打开WIN-B

how to achieve this using Javascript? 如何使用Javascript实现这一目标?

Thanks in advance 提前致谢

Given: 鉴于:

var myWindow = open("foo.bar");

Old method: Change the window object's name property: 旧方法:更改窗口对象的name属性:

myWindow.name = "...";
// in foo.bar:
setInterval(someFunctionToCheckForChangesInName, 100);

HTML5 method: Call the window object's postMessage method: HTML5方法:调用window对象的postMessage方法:

myWindow.postMessage("...", "*");
// in foo.bar:
(window.addEventListener || window.attachEvent)(
  (window.attachEvent && "on" || "") + "message", function (evt) {
    var data = evt.data; // this is the data sent to the window
    // do stuff with data
  },
false);

A similar question was just asked recently: 最近刚刚问了一个类似的问题:

Stack Overflow question: Quickest way to pass data to a popup window I created using window.open()? Stack Overflow问题: 将数据传递到我使用window.open()创建的弹出窗口的最快方法?

Using that as a base (and provided Parent and WIN-A are on the same domain): 使用它作为基础(并提供父和WIN-A在同一个域):

// Put outside click handler
var winA = null;

// Put inside click handler

if(!winA){
    // Store the return of the `open` command in a variable
    var winA = window.open('http://www.mydomain.com/page1');
} else {
    var title = winA.document.title;
    // Do something with title
    var winB = window.open('http://www.mydomain.com/page2');
}

When you call window.open, it returns a reference to the newly opened window. 当您调用window.open时,它会返回对新打开的窗口的引用。 You can store the references to the windows you open in an array, and then iterate that array when you need to open another new window. 您可以将引用存储在数组中打开的窗口中,然后在需要打开另一个新窗口时迭代该数组。

Gabriel 加布里埃尔

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM