Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Call a JavaScript function across browser tabs

Tags:

javascript

I have two browser tabs, tab1 and tab2.

I have a function called execute in tab1, which I would like to call from the page in tab2.

Is that possible and if so how?

like image 837
kumar Avatar asked Apr 10 '10 18:04

kumar


2 Answers

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();
like image 109
scunliffe Avatar answered Sep 23 '22 14:09

scunliffe


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.

like image 21
Alex from Jitbit Avatar answered Sep 22 '22 14:09

Alex from Jitbit