简体   繁体   中英

How to Communicate between two browser windows?

I have parent browser window P . on clicking a button a new browser window WIN-A is opened. then again pressing the same button it should read the title of the WIN-A window and open WIN-B

how to achieve this using Javascript?

Thanks in advance

Given:

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

Old method: Change the window object's name property:

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

HTML5 method: Call the window object's postMessage method:

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()?

Using that as a base (and provided Parent and WIN-A are on the same domain):

// 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. 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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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