Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can I control two browser windows with one HTML5 app?

I'd like my HTML5 app to draw onto two different screens. This (I think) means that I need have two distinct browser windows, one on each screen. Is this possible? It seems that I'd really have to load the same app into two windows, and somehow have the windows communicate to each other. I couldn't find an example of how to accomplish this. How can I make it happen?

For extra wonderfulness: There may not be a server involved, just an app served locally from the filesystem.

like image 686
Ned Batchelder Avatar asked Mar 11 '11 19:03

Ned Batchelder


1 Answers

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.

like image 51
josh3736 Avatar answered Sep 19 '22 20:09

josh3736