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

pra*_*een 7 javascript

我有父浏览器窗口P. 单击按钮时,将打开一个新的浏览器窗口WIN-A.然后再次按下相同的按钮,它应该读取WIN-A窗口的标题并打开WIN-B

如何使用Javascript实现这一目标?

提前致谢

Eli*_*rey 5

鉴于:

var myWindow = open("foo.bar");
Run Code Online (Sandbox Code Playgroud)

旧方法:更改窗口对象的name属性:

myWindow.name = "...";
// in foo.bar:
setInterval(someFunctionToCheckForChangesInName, 100);
Run Code Online (Sandbox Code Playgroud)

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);
Run Code Online (Sandbox Code Playgroud)

  • 我从未见过(maybe_present_func_one || possible_present_func_two)(args,args); 技术之前.凉. (2认同)

Dou*_*ner 3

最近刚刚问了一个类似的问题:

堆栈溢出问题:将数据传递到我使用 window.open() 创建的弹出窗口的最快方法?

使用它作为基础(并且假设 Parent 和 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');
}
Run Code Online (Sandbox Code Playgroud)