Call a JavaScript function across browser tabs

JavaScript can not do cross-tab scripting in the browser (it is a security risk).

If however the second tab was opened from a window.open() call, and the browsers settings were set up such that new popup windows open in a new tab instead -- then yes, "tab1" can talk to "tab2".

The first tab/window is called the opener and thus the new tab can call functions on the opener using this format:

opener.doSomething();

Likewise, the opener can call functions on the new tab/popup, by using the variable it created when creating the popup window.

var myPopup = window.open(url, name, features);
myPopup.doStuffOnPopup();

There's a tiny open-source component to sync/lock/call code in multiple tabs that allows you send messages between tabs (DISCLAIMER: I'm one of the contributors!)

https://github.com/jitbit/TabUtils

That can be called like this:

TabUtils.BroadcastMessageToAllTabs("messageName", data);

And then in another tab:

TabUtils.OnBroadcastMessage("messageName", function (data) {
    //do something
});

It is based on the onstorage event, you can simply modify the code for you need, it's very simple.

Tags:

Javascript