gpt4 book ai didi

javascript - 首次打开浏览器窗口/选项卡后执行 JavaScript 代码

转载 作者:搜寻专家 更新时间:2023-10-31 22:40:18 24 4
gpt4 key购买 nike

有没有一种方法可以在浏览器中的窗口或选项卡打开时仅执行一次 JavaScript 代码,然后在该窗口/选项卡的整个生命周期中不再执行一次(即使导航离开时)?

最佳答案

像这样使用 window.sessionStorage 的一种方法。

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.

关于javascript - 首次打开浏览器窗口/选项卡后执行 JavaScript 代码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38361392/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com