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?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With