Chrome extension - storage change listener in popup
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>