1. This site uses cookies. By continuing to use this site, you are agreeing to our use of cookies. Learn More.

Setting a cookie with xenforo.js: $.setCookie('name', 'value', 'expires)

Discussion in 'XenForo Development Discussions' started by Chris D, Nov 7, 2012.

  1. Chris D

    Chris D XenForo Developer Staff Member

    xenforo.js contains this function:

    Code:
    		/**
    		 * Sets a cookie.
    		 *
    		 * @param string cookie name (escaped)
    		 * @param mixed cookie value
    		 * @param string cookie expiry date
    		 *
    		 * @return mixed cookie value
    		 */
    		setCookie: function(name, value, expires)
    		{
    			console.log('Set cookie %s=%s', name, value);
    
    			document.cookie = XenForo._cookieConfig.prefix + name + '=' + encodeURIComponent(value)
    				+ (expires === undefined ? '' : ';expires=' + expires.toGMTString())
    				+ (XenForo._cookieConfig.path  ? ';path=' + XenForo._cookieConfig.path : '')
    				+ (XenForo._cookieConfig.domain ? ';domain=' + XenForo._cookieConfig.domain : '');
    
    			return value;
    		},
    I am using the following syntax in <script type="text/javascript"> tags in a template:

    $.setCookie('name', 'value')

    This successfully sets a cookie called "name" with a value of "value". By default, as no expiry time is specified, it creates a session cookie.

    Can anyone help me with the correct syntax to specify an expiry date?

    Thanks :)
     
    timothy259856, DeltaHF and Marcus like this.
  2. cclaerhout

    cclaerhout Well-Known Member

    I had the same problem with my addon ToogleMe. Here is a way to do it:
    Code:
            var expires = 7; // number of days
            expires = new Date(new Date().getTime() + expires * 86400000); // milliseconds in a day
    The cookie has now an expiration date... and shouldn't be deleted any more when browser is closed
     

Share This Page