I’m creating both web app and react chrome extension. I want the extension to show current web app auth status (stored in cookies). The following code below works (background script listens to cookies changes and store current value in storage, and popup script pulls every 1s the current value from storage), but I wonder whether this pulling is a right way to do it. I tried using chrome.storage.onChanged
in popup script, but it was fired only once.
background.js
const domainName = 'localhost' // address of my web app
const cookieName = 'user'
chrome.cookies.onChanged.addListener(({ cookie, removed: isBeingRemoved }) => {
if (cookie.domain === domainName && cookie.name === cookieName) {
chrome.storage.sync.set({
[cookieName]: !isBeingRemoved
? cookie.value
: null,
})
}
})
popup.jsx
const [user, setUser] = useState(null)
const pullVariablesFromStorage = () => {
chrome.storage.sync.get(['user'], function ({ user }) {
setUser(user)
})
}
useEffect(() => {
pullVariablesFromStorage()
const intervalId = setInterval(() => {
pullVariablesFromStorage()
}, 1000)
return () => clearInterval(intervalId)
}, [])
return (
<div>{user ? `Hi ${user}` : 'sign in using web app'}</div>
)