javascriptphpwordpressunlink

Unlink js file after execution


I want to remove my scripts file after it executes. It should be removed from all session. I linked file in functions.php for child theme:

function tutsplus_enqueue_custom_js() {
    wp_enqueue_script('custom', get_stylesheet_directory_uri().'/scripts/redirect.js');
}

As I said - it should be executed only once in whole session, not page. I know that it should be done with unlink but I don't know how to write a condition that will remove this file from whole session only when it was executed . Can you help me?

new script:

let executed = window.sessionStorage.getItem("sessionCodeExecuted")
console.log(executed)
if (executed != 1) {
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", 1);
}

Solution

  • You can use sessionStorage to check if the script has been executed and store this info there. Then, do a check if the value exists. If it does, prevent the code from executing on next page reload. Please note that when you close and reopen the browser, the code will execute again (it seems this is exactly what you need).

    (function(){
      let executed = window.sessionStorage.getItem("sessionCodeExecuted");
    
      if (!sessionStorage.getItem('sessionCodeExecuted')) {
          sessionStorage.setItem('sessionCodeExecuted', 'yes');
      }
      
      if (executed) return;
    
      /* below script will execute only once during the current browser session. */
    
      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;
              }
    
          }
      }
    })();