首页 > 解决方案 > 每个会话只运行一次 JS 文件

问题描述

我有这个脚本的 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 但脚本仍在运行。怎么了?

标签: javascriptphpwordpresssession

解决方案


如果是 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);

推荐阅读