每个会话只运行一次 JS 文件

Posted

技术标签:

【中文标题】每个会话只运行一次 JS 文件【英文标题】:Run JS file only once per session 【发布时间】:2021-07-16 17:56:50 【问题描述】:

我有这个脚本的 JS 文件: (我编辑了我的脚本并添加了sessionStorage检查)

let executed = window.sessionStorage.getItem("sessionCodeExecuted")
console.log(executed)
let uri = window.location;
let lang = window.navigator.language;
if (executed != 1) 
if( uri.href.indexOf('lang') < 0) 
if ((lang != 'ru-RU') && (lang != 'ru'))
eng = window.location.href.includes('https://www.site/en/');

if (eng == false)
let re = "https://www.site/";
let url = window.location.href;
let newstr = url.replace(re, 'https://www.site/en/');
newstr += "?currency=USD";
window.location.href = newstr;
   
  
 
window.sessionStorage.setItem("sessionCodeExecuted", 1);

我只想在每个会话中运行一次。我在functions.php中开始使用这段代码:

  if (!session_id()) 
        session_start();
    

console.log 写入 1 但脚本仍在运行。怎么了?

【问题讨论】:

您到底遇到了什么问题?如果您想基于 PHP 会话限制此代码,则在会话中存储一条信息,告诉它是否已经运行并使用 AJAX 与客户端通信。 如果你想在浏览器的一个会话中运行代码,你可以为此创建一个cookie,值为0。这意味着当用户结束会话时cookie将被删除浏览器。检查此 cookie 是否存在 【参考方案1】:

如果是 javascript,为什么不直接使用 sessionStorage

https://developer.mozilla.org/en-US/docs/Web/API/Web_Storage_API#sessionStorage

例如:

let mySessionLang = "ru-RU";
sessionStorage['mySession'] = mySessionLang;
let readValue = sessionStorage['mySession'];
console.log(readValue);

【讨论】:

我已经编辑了我的问题并添加了 sessionStorage。请再检查一遍好吗? 现在对你有用吗?你想让我检查什么? 不,它不起作用。我在我的问题中写了一个带有 storageSession 的脚本【参考方案2】:

您可以尝试将代码包装在 if 块中,该块检查 session storage 中的标志。

if (window.sessionStorage.getItem("sessionCodeExecuted")) 
    let uri = window.location;
    let lang = window.navigator.language;

    if (uri.href.indexOf("lang") < 0) 
        if (lang != "ru-RU" && lang != "ru") 
            eng = window.location.href.includes("https://www.site/en/");

            if (eng == false) 
                let re = "https://www.site/";
                let url = window.location.href;
                let newstr = url.replace(re, "https://www.site/en/");
                newstr += "?currency=USD";
                window.location.href = newstr;
            
        
    

    window.sessionStorage.setItem("sessionCodeExecuted", true);

这个 sn-p 无法正常运行,因为它是沙盒的,但你明白了。

【讨论】:

我已经编辑了我的问题并添加了 sessionStorage。请再检查一遍好吗?

以上是关于每个会话只运行一次 JS 文件的主要内容,如果未能解决你的问题,请参考以下文章

一段js代码怎么只运行一次

Cucumber-Java:避免多个登录并在多个独立场景中使用相同的会话

完成就绪状态后,清除缓存后,JS函数只会运行一次?

Next.js 只运行一次 getServerSideProps,next/router 访问时不获取新数据

每个 Spek 套件运行一次数据库

创建js as3 flash canvas js框架代码运行一次