Answer the question
In order to leave comments, you need to log in
How to implement tab-safe read/write to localStorage?
I was doing my own implementation of updating tokens for JWT authentication, I ran into the problem of synchronizing the update between several open tabs.
The essence of the problem: if you use localStorage to synchronize (the isRefreshing flag, which indicates that the token is already being updated at the moment, therefore the rest of the requests must wait and fly to the server with the new token after a while), then you can catch the situation when, after the token has become obsolete the request can fly from two tabs at the same time.
In fact, the second tab does not have time to track the flag change in localStorage, which was made by the first tab, because of which the second tab starts another update of the tokens, which leads to incorrect work of the program.
if (!isRefreshing()) { // проверка на то, обновляется ли токен в данный момент
// проверка в другой вкладке фактически будет выполнена в данный момент времени
updateRefreshFlag(true);
// чтобы код был безопасным, вторая вкладка должна делать проверку в этот момент исполнения кода в первой вкладке
// некоторый код обновления токена
}
function isRefreshing() {
return JSON.parse(document.localStorage.getItem('is_refreshing'))
}
function updateRefreshFlag(v) {
document.localStorage.setItem('is_refreshing', v)
}
<body>
<button id="btn">
toogle flag
</button>
<script>
const btn = document.getElementById('btn')
btn.addEventListener('click', () => {
setFlag(!getFlag())
});
setFlag(true)
function setFlag(value) {
window.localStorage.setItem('flag', value)
}
function getFlag() {
return JSON.parse(window.localStorage.getItem('flag'))
}
</script>
</body>
<body>
<script>
performAction()
function setFlag(value) {
window.localStorage.setItem('flag', value)
}
function getFlag() {
return JSON.parse(window.localStorage.getItem('flag'))
}
function performAction() {
const flagValue = getFlag()
console.log('flag value: ', flagValue)
if (flagValue) {
console.log('flag value === true, set false then')
setFlag(false)
}
}
</script>
</body>
Answer the question
In order to leave comments, you need to log in
Alas, the spec clearly says:
4.5 Threads
Because of the use of the storage mutex, multiple browsing contexts will be able to access the local storage areas simultaneously in such a manner that scripts cannot detect any concurrent script execution.
lockState=++localStorage['lockState'];
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question