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>
)
I resolved the issue by using messages (I also forgot about getting cookies when opening popup), here's the outcome:
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.runtime.sendMessage({
type: 'cookie_change',
key: cookieName,
value: !isBeingRemoved ? cookie.value : null,
})
}
})
const [user, setUser] = useState(null)
useEffect(() => {
// get cookies when opening popup
chrome.cookies.getAll({ domain: 'localhost' }).then((cookies) => {
cookies.forEach(({ name, value }) => {
if (name === 'user') {
setUser(value)
}
})
})
// while popup is opened wait for messages
chrome.runtime.onMessage.addListener((message) => {
if (message.type === 'cookie_change' && message.key === 'user') {
setUser(message.value)
}
})
}, [])
return <div>{user ? `Hi ${user}` : 'sign in using web app'}</div>