0

I am developing a JavaScript for a webpage. This script has to create a popup, when the user is idle for a certain time. When the popup shows up, the user can choose to either close the popup or to minimize it.

In case of closing the popup, further opened pages within the website shall not open the popup anymore. In case of minimizing, it should not do either. Nonetheless when the user has a certain idle time on any page the first time, it shall appear.

It works in so far, that the pop up is created and also the closing of the pop works (and that it does not open anymore). But it does not work a refresh of the page anymore. So the storing does not work. And I know it is, because of my variables and a refresh also restarts the script again, so the initialization of the variables does rewrite the session value.

So basically my question is: How do it do the 1st time initialization of the variables, which than are furtherly used after a refresh?

My code is the following:

var isClosed = new Boolean(false);
var isShrinked = new Boolean(false);
var test = "Tesst";
sessionStorage.setItem("session", isClosed=false);

function close_popup() {
     $('#' + 'box').fadeOut('slow');
     sessionStorage.setItem("session", isClosed=true);
}

(function idelor(){

document.onclick = document.onmousemove = document.onkeypress = function() {
    idleCounter = 0;
};

window.setInterval(function() {
    if (sessionStorage.getItem("session").toString() == "false") {
        if (isShrinked == false) {
            if (++idleCounter >= IDLE_TIMEOUT) {
                var scriptCode = document.createElement('p');
                scriptCode.id = 'Sentotal';
                document.getElementsByTagName('body')[0]
                        .appendChild(scriptCode);
                document.getElementById("Sentotal").innerHTML = boxTotal;
            }
        }
    }
}, interval);}());
Kaibear
  • 95
  • 1
  • 2
  • 15
  • 1
    Sounds like cookiebar behaviour => store in a cookie? Or do you want to present it to regular visitors too? Try `localStorage` as the persistence to data is [different](http://stackoverflow.com/questions/5523140/html5-local-storage-vs-session-storage) compaired to `sessionStorage`. – Tim Vermaelen Sep 29 '16 at 15:05
  • When I use localStorage, wouldn't it get overwritten the same way here? I thought session would store the information for the actual tab and even F5s of the Tab. – Kaibear Sep 29 '16 at 15:08
  • webStorage stores strings. What values are you actually seeing stored? Also read up on differences between session and localstorage...your interpretation isn't quite right – charlietfl Sep 29 '16 at 15:08
  • I can totally do that with strings, and also edited to localstorage. But the results are the same. Highly possible due to the overwrite in the start of the script. But how do I bypass that? – Kaibear Sep 29 '16 at 15:21

2 Answers2

1

You can use cookie for this matter.

//A simple function to get the value stored in cookie;
var getCookie = name =>
  document.cookie.split(';')
  .map(token => token.trim('').split('='))
  .reduce((prev, curr) =>
    (prev[curr[0]] = curr[1]) && prev, {})[name],
  myPopup = () => {
    if (!getCookie('noPopUp')) {
      console.log('your popup logic');
      document.cookie = 'noPopUp=true'
    }
  },
  reset = () => {
    document.cookie = 'noPopUp=true; expires=' + new Date();
  };

reset(); //Remove this and myPopUp will do nothing until you restart your browser.
myPopUp();
myPopUp();

Cookie resets (by default) when browser closes.

Hin Fan Chan
  • 1,543
  • 10
  • 11
  • That's great! Worked for me now! I attach the code I produced in an answer to my question. – Kaibear Sep 30 '16 at 12:39
  • Great to hear that. Just a small suggestion btw. You can use setTimeout with a handler and reset the handler in your onClick function instead of setInterval. That way you can skip ifs and the logic want be called over and over again as you simply want it to launch once. – Hin Fan Chan Sep 30 '16 at 16:04
0

I used Hin Fan Chan's suggestion of using cookies, and have the following, stable working solution coded:

Just two variables now as constant names for the Cookies:

var CLOSE_CONSTANT = "CloseCookie";
var MINIMIZE_CONSTANT = "MinimizeCookie";

Simple functions for creating and getting the cookies. Note, that "error" in getCookie(...) is very important for the initialization of the script!:

function setCookie(name, state) {
var cname = name;
var value = state;
document.cookie = cname + "=" + value;
}

function getCookie(cname) {
var name = cname + "=";
var ca = document.cookie.split(';');
for (var i = 0; i < ca.length; i++) {
    var c = ca[i];
    while (c.charAt(0) == ' ') {
        c = c.substring(1);
    }
    if (c.indexOf(name) == 0) {
        return c.substring(name.length, c.length);
    }
}
return "error";
}

I also build a cookieChecker(...) function, which automatically fills error-Cookies (those, who are not existing atmo) with "false":

function cookieChecker(name) {
switch (getCookie(name)) {
case "error":
    setCookie(name, "false");
    break;
default:
    break;
}
}

Now the final function, which is the only function being opened by the HTML. cookieChecker(...) is used twice: For the minimization and the closing of the popup. These two functions simply set the state of a cookie to true (and fading the box out):

(function idelor() {

var minutes = false;
var interval = minutes ? 60000 : 1000;
var IDLE_TIMEOUT = 5;
var idleCounter = 0;

document.onclick = document.onmousemove = document.onkeypress = function() {
    idleCounter = 0;
};
cookieChecker(MINIMIZE_CONSTANT);
cookieChecker(CLOSE_CONSTANT);

window
        .setInterval(
                function() {
                    switch (getCookie(CLOSE_CONSTANT) + " "
                            + getCookie(MINIMIZE_CONSTANT)) {
                    case "false false":
                        if (++idleCounter >= IDLE_TIMEOUT) {
                            var scriptCode = document.createElement('p');
                            scriptCode.id = 'Sentotal';
                            document.getElementsByTagName('body')[0]
                                    .appendChild(scriptCode);
                            document.getElementById("Sentotal").innerHTML = BOXTOTAL;
                        }
                    default: break;
                    }
                }, interval);
}())
Kaibear
  • 95
  • 1
  • 2
  • 15