【问题标题】:Run JS file only once per session每个会话只运行一次 JS 文件
【发布时间】: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 是否存在

标签: javascript php wordpress session


【解决方案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。请再检查一遍好吗?
猜你喜欢
  • 2014-09-24
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-03-12
  • 2017-05-24
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多