across-tabs
across-tabs copied to clipboard
Easy communication between cross-origin browser tabs. Simplified "CORS"ing!
AcrossTabs - Easy communication between cross-origin browser tabs.
- Features
- Installation
- Flow diagram
- Usage
- API
- Browser support
- Development Stack
- Process
- Scripts
- Contributing
- Roadmap
- Authors
- Copyright and license
Features
- Safely enables cross-origin communication among different browser tabs. Uses
PostMessageAPI for communication. - Easy to hook custom callback at various levels. Eg: executing a custom method in Child's tab on receiving a message from Parent tab.
- Option to provide
data-tab-opener="name"attribute on the target link/button(which opens up a new tab), so that it remains to disable untilChildtab initiates a handshake and is received by theParenttab - Fully fledged API to get information regarding the tabs(Parent and Child tabs) and other communication-related methods.
- Exports in a UMD format i.e. library works everywhere.
- Only
~4 KBgzipped.
Installation
- Via npm
$ npm install across-tabs
- Via bower
$ bower install across-tabs
- Via cdnjs, using
<script>tag
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/across-tabs/1.0.0/across-tabs.min.js"></script>
Note: Use the desired version of the library in place of 1.0.0. Checkout cdnjs across-tabs.
Flow Diagram
- Opener/Parent tab(
P) opens up a new Child tab(C). Cinitiates a handshake with thePtab by sending apostMessage.Packnowledges the request and sendsCit's identity i.e.UUIDalong withPinformation.- This sets up a communication channel between Parent and Child tab.
- Now,
PandCcan share custom messages with each other. - Whenever
Cgets closed/refreshed,Pis notified. - Whenever
Pis closed/refreshed, all children ofPtab gets notified.
Explanation of diagram
- Parent(
P) opens Child tab(C1) att=1. c1a- WhenC1initiates a handshake with the Parent.P1- WhenPreceivesC1message.P2-Packnowledges the request and sends theC1its identity.c1b- WhenC1receives an acknowledgement message along with identity fromP.
Total Tabs Associated: 1 | Opened Tabs: 1 | Closed Tabs: 0
- Parent(
P) opens CHild tab(C2) att=10. c2a- WhenC2initiates a handshake with the Parent.P3- WhenPreceivesC2message.P4-Packnowledges the request and sends theC2its identity.c2b- WhenC2receives acknowledgemnet message along with identity fromP.
Total Tabs Associated: 2 | Opened Tabs: 2 | Closed Tabs: 0
c1c- TabC1closes.P5-Pis notified about theC1. Parent updates the list.
Total Tabs Associated: 2 | Opened Tabs: 1 | Closed Tabs: 1
- Parent(
P) opens CHild tab(C3) att=25. c3a- WhenC3initiates a handshake with the Parent.P6- WhenPreceivesC3message.c2c- TabC2sends acustommessage.P7- WhenPreceives a message from tabC2. It processes it.P8-Packnowledges the request and sends theC3its identity.c3b- WhenC3receives acknowledgemnet message along with identity fromP.
Total Tabs Associated: 3 | Opened Tabs: 2 | Closed Tabs: 1
- When Parent Tab
Pis closed, all the opened tabs are notified about it.
Usage
Create an instance / reference before using.
Opener(Parent) tab
var config = {
onHandshakeCallback: function () { ... },
onPollingCallback: function () { ... },
onChildCommunication: function () { ... }
}
var parent = new AcrossTabs.Parent(config);
Constructor accepts a configurable Object with the following keys.
heartBeatInterval: The time interval for polling tabs statusesremoveClosedTabs: Pass it astrueto have only opened tabs in the listshouldInitImmediately: Pass it asfalseto create an instance but initialize it lateronHandshakeCallback: Callback to be called when a successful connection has been establishedonChildCommunication: Callback to be called when child sends messageonPollingCallback: Callback to be called every time a tab is polled for its statusorigin: whitelistoriginfor securingpostMessagecommunication. It will discard the malicious messages trying to trick the behavior. Eg. http://example.comparse: parser used when parsing messages, defaults toJSON.parsestringify: stringifier used when converting data into messages, defaults toJSON.stringify
| Config Keys | default | accepts |
|---|---|---|
| heartBeatInterval | 500 msec | A number representing milliseconds |
| removeClosedTabs | false | Boolean |
| shouldInitImmediately | true | Boolean |
| onHandshakeCallback | Undefined | Function as callback |
| onChildCommunication | Undefined | Function as callback |
| onPollingCallback | Undefined | Function as callback |
| origin | '*' | String(url) |
| parse | JSON.parse | Function |
| stringify | JSON.stringify | Function |
New(Child tab)
var config = {
onReady: onReady,
onInitialize: onInitialize,
isSiteInsideFrame: false, // dont set if not required
handshakeExpiryLimit: 4000, // msec
onParentDisconnect: onParentDisconnect,
onParentCommunication: onParentCommunication
};
var child = new AcrossTabs.Child(config);
Constructor accepts a configurable Object with the following keys.
handshakeExpiryLimit: Time to wait for getting an acknowledgement from Parent window for child's requestonReady: Callback to be invoked once child instance is readyonInitialize: Callback when a child instance is actually initiatedonParentDisconnect: Callback to be invoked when Parent gets disconnectedonParentCommunication: Callback to be invoked whenever Parent communicates with the child tabisSiteInsideFrame: If the library is loaded inside an iframe in the child tab, this needs to be settruefor maintaining proper window/frame(s) referencesorigin: whitelistoriginfor securingpostMessagecommunication. It will discard the malicious messages trying to trick the behavior. Eg. http://example.comparse: parser used when parsing messages, defaults toJSON.parsestringify: stringifier used when converting data into messages, defaults toJSON.stringify
| Config Keys | default | accepts |
|---|---|---|
| handshakeExpiryLimit | 5000 msec | A number representing milliseconds |
| isSiteInsideFrame | null | If child tab has actual site in a fram |
| onReady | Undefined | Function as callback |
| onInitialize | Undefined | Function as callback |
| onParentDisconnect | Undefined | Function as callback |
| onParentCommunication | Undefined | Function as callback |
| origin | '*' | String(url) |
| parse | JSON.parse | Function |
| stringify | JSON.stringify | Function |
Example is included in the example folder. Vanilla JS and Vue js versions are there to test out.
Note: Run npm install if you wish to run vuejs example since the example needs the vue-js library to work.
API
Refer above section on how to create an instance before hitting API methods.
Opener Tab(Parent) Methods
-
openNewTabSaves
datain specifickeyin sessionStorage. If the key is not provided, the library will warn. Following types of JavaScript objects are supported:Parameter Description config For opening a new tab i.e. URL and windowName parent.openNewTab({url: 'http://example.com', windowName: 'AcrossTab'}); -
enableElementsLinks / buttons can be given a data attribute:
data-tab-opener="name". On clicking, the library finds elements with that attribute and addsdisabled="disabled"attribute to that element. Thedisabledattribute is removed once the Child tab communicates back to the opener i.e. Parent. Though, this method is called internally but can also be invoked(may be within a timer) to be on a safer side.parent.enableElements(); -
getAllTabsReturns the list of all the tabs. If
removeClosedTabs: trueis provided while instantiating, it will return only the opened tabs as closed tabs would be removed.parent.getAllTabs() -
getOpenedTabsReturns the list of all
openedtabs.parent.getOpenedTabs(); -
getClosedTabsReturns the list of all
closedtabs. IfremoveClosedTabs: trueis provided while instantiating, it will return empty list as closed tabs would be removed.parent.getClosedTabs(); -
closeAllTabsCloses all the opened tabs.
parent.closeAllTabs() -
closeTabCloses a particular tab whose id is provided.
Parameter Description id id of the tab to be closed parent.closeTab('57cd47da-d98e-4a2d-814c-9b07cb51059c'); -
broadCastAllSends a same
messageto all the opened tabs.Parameter Description msg msg to be ent parent.broadCastAll('Hello my dear Child! A greeting from Parent.'); -
broadCastToSends a
messageto a particular opened tab.Parameter Description id id of the tab to send an msg msg msg to be sent parent.broadCastTo('57cd47da-d98e-4a2d-814c-9b07cb51059c', 'Hey! Can you run the script: worker.js? Thanks!');
New Tab(Child) Methods
-
getTabInfoReturn id, name, and parentName of the child tab.
child.getTabInfo(); -
sendMessageToParentSends a
messageto theParenttab.Parameter Description msg msg to be sent child.sendMessageToParent('Hey Parent! I\'m done with my work.');
Browser Support
Tested in Chrome, Firefox and IE(versions >= 9).
Sites using across-tabs
- app.vwo.com
- [Add your site] - See Contributing section
Development Stack
- Webpack based
srccompilation & bundling anddistgeneration. - ES6 as a source of writing code.
- Exports in a UMD format so the library works everywhere.
- Linting with ESLint.
- ES6 test setup with Karma, Jasmine and isparta.
- Test coverage with Istanbul and Coveralls.
Process
ES6 source files
|
|
webpack
|
+--- babel, eslint
|
o--- tests and covergae
|
ready to use
library
in UMD format
Scripts
npm run build- produces production version(minified) of the library under thedistfoldernpm run dev- produces development version(un minified) of the library and runs a watcher to detect file changes.npm run test- well ... it runs the tests :)
Contributing
- Fork the repo on GitHub.
- Clone the repo on a machine.
- Execute
npm installandnpm run dev. - Create a new branch
<fix-typo>and do your work. - Run
npm run buildto build dist files andnpm run testto ensure all test cases are passing. - Commit your changes to the branch.
- Submit a Pull request.
Note: If adding site to the list of sites using across-tabs, please mention where to verify this in the PR description.
Roadmap
- Having a Queue mechanism to deal with loads of async events.
- Promise based
Parent-Childcommunication. Will help in sending window-specific data to and fro apart from custom data messages. - E2E testing so that the behavior can be tested automatically.
- Maintaining and adding more enhancements as and when required. Open to everyone's suggestions.
Authors
Copyright and license
The MIT license (MIT)
Copyright (c) 2017-2019 Wingify Software Pvt. Ltd.
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
