Skip to content

Instantly share code, notes, and snippets.

@GoodBoyDigital
Last active January 6, 2025 13:30
Show Gist options
  • Save GoodBoyDigital/8908bd2231c3417671cad8f3c38fff6d to your computer and use it in GitHub Desktop.
Save GoodBoyDigital/8908bd2231c3417671cad8f3c38fff6d to your computer and use it in GitHub Desktop.
/**
* This script is designed to detect if an unintended webview reload has occurred due to high memory usage.
* It uses the localStorage to store a 'tick' value which is the timestamp of the last frame.
* It also uses a 'safe-reload' flag to determine if the reload was intentional.
*/
if(localStorage.getItem('safe-reload') === 'true' || !localStorage.getItem('tick')) {
// If 'safe-reload' is set to true or 'tick' is not present in localStorage, it means:
// - The reload was intentional (safe-reload is true)
// - This is the first load (tick is not present)
// In both cases, we clear the 'safe-reload' flag.
localStorage.removeItem('safe-reload');
} else {
// If 'safe-reload' is not true and 'tick' is present, it means the page was reloaded.
const lastTick = parseFloat(localStorage.getItem('tick') as string);
const now = performance.now();
const diff = now - lastTick;
// If the difference between the current time and the last tick is less than 3000 milliseconds (3 seconds),
// it indicates that the page was reloaded within 3 seconds, which is considered an unexpected reload.
if(diff < 3000) {
console.warn('unsafe reload happened', diff);
// Here you can add code to track the reload event, e.g., sending data to a server or logging it.
}
}
// This function sets the 'tick' value in localStorage to the current timestamp on each animation frame.
requestAnimationFrame(() => {
localStorage.setItem('tick', performance.now().toString());
});
// This event listener sets the 'safe-reload' flag to true when the window is about to unload. THis would not be called if the window
// force reloaded due to memory constraints
window.onbeforeunload = () => {
localStorage.setItem('safe-reload', 'true');
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment