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
You could try wrapping your code in an
if
block which checks for a flag in the session storage.This snippet won’t run properly because it is sandboxed, but you get the idea.
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: