Skip to content

Instantly share code, notes, and snippets.

@kamal-hossain
Last active December 28, 2020 03:42
Show Gist options
  • Save kamal-hossain/8a29c55099d0a100c65699bb0ddaf607 to your computer and use it in GitHub Desktop.
Save kamal-hossain/8a29c55099d0a100c65699bb0ddaf607 to your computer and use it in GitHub Desktop.
Share data between react app in browser tabs ( must be same protocol, origin and port) , https://dev.to/kamalhossain/send-data-between-tabs-in-react-app-2ehi
import React from 'react'
import './App.css'
function App() {
const [isOpnnedAlready, setIsOpnnedAlready] = React.useState(false)
const channel = React.useMemo(() => new BroadcastChannel('couldBeAnything'), [])
React.useEffect(() => {
channel.postMessage({
isOpnnedAlready: true,
})
channel.addEventListener('message', (e) => {
setIsOpnnedAlready(e.data.isOpnnedAlready)
})
return channel.close
}, [])
function refreshPage() {
window.location.reload()
}
return (
<div class="App">
{!isOpnnedAlready ? (
<h1>Something happening in the dom</h1>
) : (
<>
<p>Only one tab could open at a time</p>
<button type="button" onClick={refreshPage}>
<span>Reload</span>{' '}
</button>
</>
)}
</div>
)
}
export default App
{
"name": "browser-tab-broadcast-react",
"version": "0.1.0",
"private": true,
"dependencies": {
"@testing-library/jest-dom": "^5.11.6",
"@testing-library/react": "^11.2.2",
"@testing-library/user-event": "^12.5.0",
"react": "^17.0.1",
"react-dom": "^17.0.1",
"react-scripts": "4.0.1",
"web-vitals": "^0.2.4"
},
"scripts": {
"start": "react-scripts start",
"build": "react-scripts build",
"test": "react-scripts test",
"eject": "react-scripts eject"
},
"eslintConfig": {
"extends": [
"react-app",
"react-app/jest"
]
},
"browserslist": {
"production": [
">0.2%",
"not dead",
"not op_mini all"
],
"development": [
"last 1 chrome version",
"last 1 firefox version",
"last 1 safari version"
]
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment