I need to refresh the page when a user returns to it from another page with the same website address (host(name)).
I use visibilityChange event to detect tab switching:
import { useEffect } from 'react';
export const useVisibilityChange = (
isHiddenCallback,
isNotHiddenCallback,
) => {
let hidden, visibilityChange;
/* istanbul ignore next */
if (typeof document.hidden !== 'undefined') {
// Opera 12.10 and Firefox 18 and later support
hidden = 'hidden';
visibilityChange = 'visibilitychange';
} else if (typeof document.msHidden !== 'undefined') {
hidden = 'msHidden';
visibilityChange = 'msvisibilitychange';
} else if (typeof document.webkitHidden !== 'undefined') {
hidden = 'webkitHidden';
visibilityChange = 'webkitvisibilitychange';
}
const handleVisibilityChange = () => {
if (document[hidden]) {
isHiddenCallback && isHiddenCallback();
} else {
isNotHiddenCallback && isNotHiddenCallback();
}
};
useEffect(() => {
document.addEventListener(visibilityChange, handleVisibilityChange, false);
return () => document.removeEventListener(visibilityChange, handleVisibilityChange, false);
// eslint-disable-next-line react-hooks/exhaustive-deps
}, []);
return { isDocumentHidden: document[hidden] };
};
I tried to store the hostname in LocalStorage and checked this value on another page. But I can not come up with a working algorithm to check a switching from the relative page.
useVisibilityChange(() => {
// ON HIDDEN CALLBACK
// if (localStorage.get('refreshed')) {
// localStorage.removeItem('refreshed');
// localStorage.setItem('origin', origin);
// }
}, () => {
// ON VISIBLE CALLBACK
if (localStorage.getItem('origin')
&& localStorage.getItem('origin') === origin
&& !localStorage.getItem('refreshed')
) {
localStorage.removeItem('origin');
localStorage.setItem('refreshed', true);
window.location.reload();
} else {
if (!localStorage.getItem('origin')) {
localStorage.setItem('origin', origin);
}
if (localStorage.getItem('refreshed')) {
localStorage.removeItem('refreshed');
}
}
});