The behavior you're describing is likely due to the way the browser handles the history state and caching of the page. When you navigate using the back and forward buttons, the browser may serve a cached version of the page, including the state of the DOM at the time you left it, which includes the toast message being visible.
To prevent the toast from reappearing when navigating back and forth, you can use JavaScript to detect when the page is loaded from the cache and then hide or remove the toast message. Here's a solution using vanilla JavaScript that you can include in your page:
window.addEventListener('load', function() {
// Check if the page was restored from the cache
if (performance.navigation.type === performance.navigation.TYPE_BACK_FORWARD) {
// Your code to hide or remove the toast message
const toast = document.querySelector('.toast-selector'); // Replace with your toast's selector
if (toast) {
toast.style.display = 'none'; // Or any other method to hide or remove the toast
}
}
});
Alternatively, if you're using a front-end framework like Vue or React, you can manage the visibility of the toast message with a state variable that is reset when the component mounts.
For Vue 3, it might look something like this:
<template>
<div v-if="showToast" class="toast">
<!-- Toast content -->
</div>
</template>
<script>
export default {
data() {
return {
showToast: true
};
},
mounted() {
if (performance.navigation.type === performance.navigation.TYPE_BACK_FORWARD) {
this.showToast = false;
}
}
};
</script>
For React, you could use the useEffect hook to detect when the component mounts:
import React, { useState, useEffect } from 'react';
const ToastComponent = () => {
const [showToast, setShowToast] = useState(true);
useEffect(() => {
if (window.performance && window.performance.navigation.type === window.performance.navigation.TYPE_BACK_FORWARD) {
setShowToast(false);
}
}, []);
return (
<>
{showToast && (
<div className="toast">
{/* Toast content */}
</div>
)}
</>
);
};
export default ToastComponent;
Please note that performance.navigation is deprecated and you should use the PerformanceNavigationTiming interface instead. However, for simplicity and broad compatibility, the above examples use performance.navigation.
Remember to replace .toast-selector with the actual selector for your toast message, and adjust the logic to fit the framework or library you're using.