سؤال

I'm using the docCookies object to set cookies on this application.

The function that I'm testing is this one:

displayWelcomeMessage = function(idElement){
    var cookieName = 'username';

    alert(docCookies.getItem(cookieName)); // NULL when cookie not set

    var defaultName = "SweetAnon",
        daysToExpire = 1,
        username = docCookies.getItem(cookieName);

    // Check if cookie was already set (user "logged")
    if (username != null && username.trim() != "") {
        displayUsername(idElement, username);
    } else {
        username = prompt("If you enter your name\nI'll try to remember you :)");
        if (username != null && username.trim() != "") {
            docCookies.setItem(cookieName, username, daysToExpire);
            displayUsername(idElement, username);
        } else {
            displayUsername(idElement, defaultName);
        }
    }
    alert(docCookies.getItem(cookieName)); // Username or 'SweetAnon'
};

Here are two alerts and they print different results between Firefox v28 and Chromium v33.0.1750.152. If I enter foobar as username I get this results:

  • Firefox prints null and then foobar.
  • Chromium it prints null and then null again.

I consider the Firefox behavior correct. But what should I do to make it work on Chromium?

هل كانت مفيدة؟

المحلول

The solution is to assign the cookie value to an object rather than a variable:

displayWelcomeMessage = function(idElement)
  {
  var cookieName = 'username',
      defaultName = "SweetAnon",
      daysToExpire = 1;

  /* assign username as a property of the current function */

  this.username = docCookies.getItem(cookieName);

  alert(docCookies.getItem(cookieName)); // NULL when cookie not set

  // Check if cookie was already set (user "logged")

  if (this.username != null && this.username.trim() != "")
      {
      displayUsername(idElement, this.username);
      } 

    else 
      {
      this.username = prompt("If you enter your name\nI'll try to remember you :)");

      if (this.username != null && this.username.trim() != "") 
        {
        docCookies.setItem(cookieName, this.username, daysToExpire);
        displayUsername(idElement, username);
        } 
      else 
        {
        displayUsername(idElement, defaultName);
        }
      }

  alert(docCookies.getItem(cookieName)); // Username or 'SweetAnon'
  };

References

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top