问题
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)?
回答1:
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.
回答2:
Here is a solution based on checking the window.history.length is 1 (i.e. the first time they've been to this window/tab). It also does a check that they've not simply refreshed the page.
if(window.history.length === 1 && performance.navigation.type !== 1){
alert("show me once per tab");
}
If you put the script you want to run once where I have my alert, it should work for what you are trying to do.
回答3:
You can use localStorage.
Local storage is per origin (per domain and protocol). All pages, from one origin, can store and access the same data.
The localStorage object stores the data with no expiration date. The data will not be deleted when the browser is closed, and will be available the next day, week, or year.
localStorage.getItem('key');
localStorage.setItem('key', 'value');
Doc: http://www.w3schools.com/html/html5_webstorage.asp
来源:https://stackoverflow.com/questions/38361392/execute-javascript-code-once-a-browser-window-tab-is-opened-for-the-first-time