Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Execute JavaScript code once a browser window/tab is opened for the first time

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)?

like image 791
Palmi Avatar asked Sep 21 '26 06:09

Palmi


1 Answers

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.

like image 70
naveen Avatar answered Sep 22 '26 19:09

naveen