第一次打开浏览器窗口/选项卡时执行JavaScript代码 [英] Execute JavaScript code once a browser window/tab is opened for the first time

查看:84
本文介绍了第一次打开浏览器窗口/选项卡时执行JavaScript代码的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当浏览器中的窗口或选项卡打开时,是否有一种方法只能执行一次JavaScript代码,然后再也不会在此窗口/选项卡的整个生命周期内(甚至在导航离开时)?

解决方案

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

  if(!window.sessionStorage.getItem(isExecuted)){
//执行代码
window.sessionStorage.setItem (isExecuted,true);
}

MDN文档 $ b


sessionStorage属性允许你访问会话Storage
对象。 sessionStorage与Window.localStorage类似,唯一的
区别是存储在localStorage中的数据没有设置过期时,存储在sessionStorage中的
数据在页面会话结束时被清除。
只要浏览器处于打开状态并且页面重新加载和恢复时,页面会话持续
在新选项卡或窗口中打开页面
将导致启动新会话
,这与
会话Cookie的工作方式不同。



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.

这篇关于第一次打开浏览器窗口/选项卡时执行JavaScript代码的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆