Is there a way to execute JavaScript code only once when a window or a tab in a browser is opened and then never again for the whole life-cycle of this window/tab (even when navigated away)?
One way to use window.sessionStorage like this.
if (!window.sessionStorage.getItem("isExecuted")) {
//execute code
window.sessionStorage.setItem("isExecuted", true);
}
MDN docs
The sessionStorage property allows you to access a session Storage object. sessionStorage is similar to Window.localStorage, the only difference is while data stored in localStorage has no expiration set, data stored in sessionStorage gets cleared when the page session ends. A page session lasts for as long as the browser is open and survives over page reloads and restores. Opening a page in a new tab or window will cause a new session to be initiated, which differs from how session cookies work.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With