skip to Main Content

I have got JS file with this script:
(I edited my script and added sessionStorage check)

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);
}

I want to run it only once per session. I started session with this code in functions.php:

  if (!session_id()) {
        session_start();
    }

console.log writes 1 but is script still running. What is wrong?

2

Answers


  1. You could try wrapping your code in an if block which checks for a flag in the 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);
    }

    This snippet won’t run properly because it is sandboxed, but you get the idea.

    Login or Signup to reply.
  2. If it’s JavaScript, why not just use sessionStorage:

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

    For example, something like:

    let mySessionLang = "ru-RU";
    sessionStorage['mySession'] = mySessionLang;
    let readValue = sessionStorage['mySession'];
    console.log(readValue);
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search