There's no need for a messy polling infrastructure using local storage or (shudder) cookies. Assuming the two pages are served from the same domain, it is trivial to implement cross-window communication so long as the second window is opened by the first.
In your main window: (click here for JSFiddle demo and here for the secondary page's code)
var win2;
function openSecondaryWindow() {
return win2 = window.open('win2.html','secondary','width=300,height=100');
}
$(function() {
if (!openSecondaryWindow()) // Try to open the window. This will likely be blocked by a popup blocker (unless you disable it).
$(document.body) // If it is blocked, clicking a link usually allows the popup to be spawned.
.prepend('<a href="#">Popup blocked. Click here to open the secondary window.</a>')
.click(function() { openSecondaryWindow(); return false; });
$('#somelink').click(function() {
if (win2) win2.doSomething(); // Obviously, you'll need to define doSomething in the second page
else alert('The secondary window is not open.');
return false;
});
});
Once the secondary window has been opened by your main window, win2
will refer to the window
object of the second page – in other words, the page's global scope. You'll have access to all of the functions and variables you've defined in the second page.
Thus, you can pass data through function calls.
win2.update({ key: 'value', ... });
From your secondary window, you can call back to functions in the main window through the opener
property, which will refer to the window
object of your main window. (This is demonstrated in the JSFiddle demo.)
Update: Intercom is a library that uses local storage to implement broadcast messaging between windows. Local storage fires an event (onstorage
) when data changes, so polling is not actually necessary. Intercom allows all pages on a domain to communicate, regardless of how they were opened.