window-communication-hook

v0.0.1arrow_drop_down
v0.0.1
STATUS
Passing
DOWNLOADS
46
VISIBILITY
Public
PUBLISHED
6 years ago
SIZE
1 KB
1 contributor
Install window-communication-hook as a package?
Copied
npm i @bit/giladshoham.react-hooks.hooks.window-communication-hook
Set Bit as a scoped registryLearn more
npm config set '@bit:registry' https://node.bit.cloud
Component Example
React
React
Vue
Angular
React Native
Add dependency... help_outline
Just
import
any of the 1 million components
and packages in Bit or NPM to the example.
import Button from '@bit/grommet.grommet.button';
import Lodash from 'lodash';
toggle layout
chevron_left
chevron_right

react-window-communication-hook

React hook to communicate among browsers contexts (windows, tabs, iframes).

Example use case: When the user presses logout in one tab, logout from every other tab

How to use it

Import

import useBrowserContextCommunication from 'react-window-communication-hook';

pass a channel name

const [communicationState, postMessage] = useBrowserContextCommunication("myGreatChannel");

communicationState contains lastMessage and messages which is an array of the messages that where send from other tabs/windows to the current one.

Use postMessage to send messages to the other browser contextes (windows, tabs, iframes)

Example

import useBrowserContextCommunication from 'react-window-communication-hook';


function App() {
  // state ({lastMessage,messages}) that comes from other browser context
  const [communicationState, postMessage] = useBrowserContextCommunication("channel");
  // Tabs, Windows etc are not listening to there own messages so
  // we need an extra local state
  const [status, setStatus] = useState("login");

  function logout() {
    setStatus("logout");
    postMessage("logout");
  }

  const shouldLogout = [communicationState.lastMessage, status].includes('logout');

  return (
    <div className="App" >
      <h1>{shouldLogout ? 'Logged Out' : 'Logged In' }</h1>
      <button onClick={logout}>Logout</button>
    </div>
  );
}

Help and resources