Foros del Web » Programando para Internet » Javascript »

De casualidad alguien tiene codigo de cookies?

Estas en el tema de De casualidad alguien tiene codigo de cookies? en el foro de Javascript en Foros del Web. Hola! Tengo un Pop Up en la web, el problema es que aparece cada vez que entras a la web.. a mi lo que me ...
  #1 (permalink)  
Antiguo 25/09/2014, 04:04
 
Fecha de Ingreso: agosto-2014
Mensajes: 294
Antigüedad: 9 años, 7 meses
Puntos: 4
Pregunta De casualidad alguien tiene codigo de cookies?

Hola! Tengo un Pop Up en la web, el problema es que aparece cada vez que entras a la web.. a mi lo que me gustaria es que solo mostrara 1 vez por dia a cada usuario.. he probado algunos codigos que hay en internet y ninguno me ha funcionado...

si no me equivoco hay que hacerlo con jquery.. pero fuf no se mucho de tema

Por lo cual si alguien lo tiene se agradecería mucho que lo comparta
  #2 (permalink)  
Antiguo 25/09/2014, 05:01
Avatar de lauser
Moderator Unix/Linux
 
Fecha de Ingreso: julio-2013
Ubicación: Odessa (Ukrania)
Mensajes: 3.278
Antigüedad: 10 años, 8 meses
Puntos: 401
Respuesta: De casualidad alguien tiene codigo de cookies?

Como esto, en js:
Código Javascript:
Ver original
  1. /** Main class */
  2. window.CookieTool = function() {};
  3.  
  4. /** Utility functions */
  5. CookieTool.Utils = {
  6.     /**
  7.      * Extend an object
  8.      * @param {Object} obj1
  9.      * @param {Object} obj2
  10.      * @return {Object} the merged object
  11.      */
  12.     extend: function(obj1, obj2) {
  13.         var ret = obj1,
  14.             prop;
  15.         for (prop in obj2) {
  16.             if(obj2.hasOwnProperty(prop)) {
  17.                 ret[prop] = obj2[prop];
  18.             }
  19.         }
  20.         return ret;
  21.     },
  22.  
  23.     /**
  24.      * Load a script asynchronously
  25.      * @param {String} src the script src
  26.      * @param {Function} callback an optionall callback
  27.      */
  28.      loadScript: (function() {
  29.         var firstjs = document.getElementsByTagName('script')[0];
  30.  
  31.         return function(src, callback) {
  32.             var s = document.createElement('script'),
  33.                 loaded;
  34.             s.async = true;
  35.             s.onload = s.onreadystatechange = function() {
  36.                 if( ! loaded && (! s.readyState || s.readyState === 'complete' || s.readyState === 'loaded') ) {
  37.                     loaded = true;
  38.                     if( callback && typeof callback === 'function' ) {
  39.                         callback.call(null, s);
  40.                     }
  41.                 }
  42.             };
  43.             s.src = src;
  44.             firstjs.parentNode.insertBefore(s, firstjs);
  45.         }
  46.      }())
  47. }
  48.  
  49. CookieTool.Config = (function() {
  50.     var config = {
  51.         'position': 'top',
  52.         'message': 'En este sitio se usan cookies para ofrecer una experiencia más personalizada. <a href="{{link}}" target="_blank">Más información</a>.<br>¿Nos consiente usar cookies?',
  53.         'link': '/cookies',
  54.         'agreetext': 'Sí',
  55.         'declinetext': 'No'
  56.     }
  57.  
  58.     return {
  59.         get: function(key) {
  60.             return config[key];
  61.         },
  62.         set: function(key, val) {
  63.             if( typeof key === 'string' ) {
  64.                 config[key] = val;
  65.             } else {
  66.                 config = CookieTool.Utils.extend(config, key);
  67.             }
  68.         }
  69.     }
  70. }());
  71.  
  72. /**
  73.  * Event API for customisation
  74.  */
  75. CookieTool.Event = (function() {
  76.     /** Where the callbacks are stored */
  77.     var events = {};
  78.     return {
  79.         /**
  80.          * Add an event listener
  81.          * @param {String} name the identifier
  82.          * @param {Function} callback
  83.          * @return undefined
  84.          */
  85.         on: function(name, callback) {
  86.             if( events[name] === undefined ) {
  87.                 events[name] = [];
  88.             }
  89.             if( typeof callback === 'function' ) {
  90.                 events[name].push(callback);
  91.             }
  92.         },
  93.         /**
  94.          * Trigger all event listeners for an identifier
  95.          * @param {String} name the identifier
  96.          * @return undefined
  97.          */
  98.         trigger: function(name) {
  99.             var cbs = events[name],
  100.                 i = 0,
  101.                 len;
  102.  
  103.             if( ! cbs ) {
  104.                 return;
  105.             }
  106.             len = cbs.length;
  107.             for (; i < len; i++) {
  108.                 cbs[i]();
  109.             }
  110.         }
  111.     }
  112. }());
  113.  
  114.  
  115. /**
  116.  * Cookie functions
  117.  */
  118. CookieTool.Cookie = {
  119.     /**
  120.      * Get a cookie value
  121.      * @param {String} key
  122.      * @return {String} the value
  123.      */
  124.     get: function(key) {
  125.         return decodeURIComponent(document.cookie.replace(new RegExp("(?:(?:^|.*;)\\s*" + encodeURIComponent(key).replace(/[\-\.\+\*]/g, "\\$&") + "\\s*\\=\\s*([^;]*).*$)|^.*$"), "$1")) || null;
  126.     },
  127.  
  128.     /**
  129.      * Set a cookie value
  130.      * @param {String} key
  131.      * @param {String} value
  132.      * @param {Number} days
  133.      * @param {String} domain
  134.      * @param {String} path
  135.      */
  136.     set: function(key, value, days, domain, path) {
  137.         var cookie = key + "=" + encodeURIComponent(value),
  138.             date;
  139.         if (days) {
  140.             date = new Date();
  141.             date.setTime(date.getTime()+(days*24*60*60*1000));
  142.             cookie += "; expires="+date.toGMTString();
  143.         }
  144.         if ( domain ) {
  145.             cookie += "; domain=" + domain
  146.         }
  147.         if( ! path ) {
  148.             path = "/";
  149.         }
  150.         cookie +=  "; path=" + path;
  151.         document.cookie = cookie;
  152.     },
  153.  
  154.     /**
  155.      * Delete a cookie
  156.      * @param {String} key
  157.      * @param {String} domain necessary for GA cookies
  158.      */
  159.     remove: function(key, domain) {
  160.         CookieTool.Cookie.set(key,"",-1, domain);
  161.     }
  162. }
  163.  
  164. /**
  165.  * Storage functions (HTML5 localStorage based) (permanent storage)
  166.  */
  167. if( window.localStorage ) {
  168.     CookieTool.Storage = {
  169.         /**
  170.          * Get a stored value
  171.          * @param {String} key
  172.          * @return {String} the value
  173.          */
  174.         get: function(key) {
  175.             return window.localStorage.getItem(key);
  176.         },
  177.         /**
  178.          * Set a value
  179.          * @param {String} key
  180.          * @param {String} value
  181.          */
  182.         set: function(key, value) {
  183.             return window.localStorage.setItem(key, value);
  184.         },
  185.         /**
  186.          * Delete a stored value
  187.          * @param {String} key
  188.          */
  189.         remove: function(key) {
  190.             return window.localStorage.removeItem(key);
  191.         }
  192.     }
  193. } else {
  194.     // Cookie based storage
  195.     CookieTool.Storage = CookieTool.Cookie;
  196. }
  197.  
  198. /**
  199.  * Main API
  200.  */
  201. CookieTool.API = {
  202.     /**
  203.      * Some status codes
  204.      */
  205.     statuses: {
  206.         'AGREE': '1',
  207.         'DECLINE': '0',
  208.         'UNDETERMINED': null
  209.     },
  210.     /**
  211.      * Set/get the current status of tracking
  212.      */
  213.     status: function(value) {
  214.         if( value === undefined ) {
  215.             return CookieTool.Storage.get('ctstatus');
  216.         }
  217.         if( CookieTool.API.statuses[value] ) {
  218.             return CookieTool.Storage.set('ctstatus', CookieTool.API.statuses[value], 365);
  219.         }
  220.         return CookieTool.Storage.set('ctstatus', value, 365);
  221.     },
  222.  
  223.     /**
  224.      * Ask for cookie consenting
  225.      */
  226.     ask: function() {
  227.         var message,
  228.             status,
  229.             body = document.body;
  230.         // Already agreed
  231.         if( CookieTool.API.status() === CookieTool.API.statuses.AGREE ) {
  232.             return CookieTool.API.agree();
  233.         }
  234.  
  235.         if( CookieTool.API.status() === CookieTool.API.statuses.DECLINE ) {
  236.             return CookieTool.API.decline();
  237.         }
  238.  
  239.         message = document.createElement('div');
  240.         message.className = 'cookietool-message cookietool-message-' + CookieTool.Config.get('position');
  241.         body.className += ' cookietool';
  242.         // No overcomplications with event listeners
  243.         message.onclick = function(e) {
  244.             var e = e || window.event,
  245.                 target = e.target || e.srcElement,
  246.                 action = target.getAttribute('data-action');
  247.             if( action && CookieTool.API[action] ) {
  248.                 CookieTool.API[action]();
  249.                 if( e.preventDefault ) {
  250.                     e.preventDefault();
  251.                 } else {
  252.                     e.returnValue = false;
  253.                 }
  254.                 message.parentNode.removeChild(message);
  255.                 body.className = body.className.replace(/\bcookietool\b/, '');
  256.                 return false;
  257.             }
  258.         }
  259.  
  260.         // onclick="" in <button>'s to fix event delegation in Safari for iPhone: http://www.quirksmode.org/blog/archives/2010/09/click_event_del.html
  261.         message.innerHTML = '<p>' + CookieTool.Config.get('message').replace(/\{\{link\}\}/g, CookieTool.Config.get('link')) + '</p><button data-action="agree" onclick="">' + CookieTool.Config.get('agreetext') + '</button> <button data-action="decline" onclick="">' + CookieTool.Config.get('declinetext') + '</button>';
  262.         body.appendChild(message);
  263.     },
  264.  
  265.     /**
  266.      * Assume implied agreement
  267.      * Note that you'll need at least somewhere in your page a link with a decline option (eg: <button onclick="CookieTool.API.decline()">I don't want cookies</button>)
  268.      */
  269.     impliedAgreement: function() {
  270.         var status = CookieTool.API.status();
  271.         switch(status) {
  272.             case CookieTool.API.statuses.DECLINE:
  273.                 CookieTool.API.decline();
  274.                 break;
  275.             // case CookieTool.API.statuses.UNDETERMINED:
  276.             // case CookieTool.API.statuses.AGREE:
  277.             default:
  278.                 CookieTool.API.agree();
  279.         }
  280.     },
  281.  
  282.     displaySettings: function(container) {
  283.         var status = CookieTool.API.status();
  284.         if( ! container ) {
  285.             return;
  286.         }
  287.  
  288.         container.className += ' cookietool-settings';
  289.         container.onclick = function(e) {
  290.             var e = e || window.event,
  291.                 target = e.target || e.srcElement,
  292.                 action = target.getAttribute('data-action');
  293.                 console.log();
  294.             if( action && CookieTool.API[action] ) {
  295.                 CookieTool.API[action]();
  296.                 CookieTool.API.displaySettings(container);
  297.                 if( e.preventDefault ) {
  298.                     e.preventDefault();
  299.                 } else {
  300.                     e.returnValue = false;
  301.                 }
  302.                 return false;
  303.             }
  304.         }
  305.  
  306.         if( status === CookieTool.API.statuses.AGREE ) {
  307.             container.innerHTML = 'Actualmente <strong>aceptas</strong> el uso de cookies en el sitio. <a role="button" data-action="decline" href="#">Pulsa aquí para no permitir cookies</a>';
  308.         } else if ( status === CookieTool.API.statuses.DECLINE ) {
  309.             container.innerHTML = 'Actualmente <strong>no aceptas</strong> el uso de cookies en el sitio. <a role="button" data-action="agree" href="#">Pulsa aquí para permitir cookies</a>'
  310.         } else {
  311.             container.innerHTML = 'Aún no has establecido tu configuración. Haz click <a role="button" data-action="agree" href="#">aquí</a> si quieres aceptar el uso de cookies, o <a role="button" data-action="decline" href="#">aquí</a> si no.';
  312.         }
  313.     },
  314.     /**
  315.      * Agree
  316.      */
  317.      agree: function() {
  318.         CookieTool.API.status('AGREE');
  319.         CookieTool.Event.trigger('agree');
  320.      },
  321.  
  322.      /**
  323.       * Decline
  324.       */
  325.      decline: function() {
  326.         CookieTool.API.status('DECLINE');
  327.         CookieTool.Event.trigger('decline');
  328.      }
  329. }
  330.  
  331. /**
  332.  * Default id for settings, allows to put the script at the footer with no worries
  333.  */
  334.  if( document.getElementById('cookietool-settings') ) {
  335.     CookieTool.API.displaySettings(document.getElementById('cookietool-settings'));
  336.  }
  337.  
  338.  
  339. /**
  340.  * Default behaviour on agree: Load google analytics and adsense if present
  341.  */
  342. CookieTool.Event.on('agree', function() {
  343.     if( window.adsbygoogle ) {
  344.         CookieTool.Utils.loadScript('http://pagead2.googlesyndication.com/pagead/js/adsbygoogle.js');
  345.     }
  346.     if( window._gaq ) {
  347.         CookieTool.Utils.loadScript(('https:' == document.location.protocol ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js');
  348.     } else if ( window.ga ) {
  349.         CookieTool.Utils.loadScript('//wwww.google-analytics.com/analytics.js');
  350.     }
  351. });
  352.  
  353. /**
  354.  * Default behaviour on decline: Delete GA cookies
  355.  */
  356.  CookieTool.Event.on('decline', function() {
  357.     var cookiestodelete = ['__utma', '__utmb', '__utmc', '__utmz', '__utmv'],
  358.         i = 0,
  359.         len = cookiestodelete.length,
  360.         domain = window.location.hostname;
  361.     if( (/^www\./).test(domain) ) {
  362.         domain = domain.substring(4);
  363.     }
  364.  
  365.     for( ; i < len; i++) {
  366.         CookieTool.Cookie.remove(cookiestodelete[i], domain);
  367.     }
  368. });
__________________
Los usuarios que te responden, lo hacen altruistamente y sin ánimo de lucro con el único fin de ayudarte. Se paciente y agradecido.
-SOLOLINUX-
  #3 (permalink)  
Antiguo 25/09/2014, 05:40
 
Fecha de Ingreso: agosto-2014
Mensajes: 294
Antigüedad: 9 años, 7 meses
Puntos: 4
Respuesta: De casualidad alguien tiene codigo de cookies?

Hola te pido mi mal conocimiento... pero que nombre de ID le tengo que dar al div para hacer funcionar esa funcion ?

Gracias y +1



Cita:
Iniciado por lauser Ver Mensaje
Como esto, en js:
Código Javascript:
Ver original
  1. /** Main class */
  2. window.CookieTool = function() {};
  3.  
  4. /** Utility functions */
  5. CookieTool.Utils = {
  6.     /**
  7.      * Extend an object
  8.      * @param {Object} obj1
  9.      * @param {Object} obj2
  10.      * @return {Object} the merged object
  11.      */
  12.     extend: function(obj1, obj2) {
  13.         var ret = obj1,
  14.             prop;
  15.         for (prop in obj2) {
  16.             if(obj2.hasOwnProperty(prop)) {
  17.                 ret[prop] = obj2[prop];
  18.             }
  19.         }
  20.         return ret;
  21.     },
  22.  
  23.     /**
  24.      * Load a script asynchronously
  25.      * @param {String} src the script src
  26.      * @param {Function} callback an optionall callback
  27.      */
  28.      loadScript: (function() {
  29.         var firstjs = document.getElementsByTagName('script')[0];
  30.  
  31.         return function(src, callback) {
  32.             var s = document.createElement('script'),
  33.                 loaded;
  34.             s.async = true;
  35.             s.onload = s.onreadystatechange = function() {
  36.                 if( ! loaded && (! s.readyState || s.readyState === 'complete' || s.readyState === 'loaded') ) {
  37.                     loaded = true;
  38.                     if( callback && typeof callback === 'function' ) {
  39.                         callback.call(null, s);
  40.                     }
  41.                 }
  42.             };
  43.             s.src = src;
  44.             firstjs.parentNode.insertBefore(s, firstjs);
  45.         }
  46.      }())
  47. }
  48.  
  49. CookieTool.Config = (function() {
  50.     var config = {
  51.         'position': 'top',
  52.         'message': 'En este sitio se usan cookies para ofrecer una experiencia más personalizada. <a href="{{link}}" target="_blank">Más información</a>.<br>¿Nos consiente usar cookies?',
  53.         'link': '/cookies',
  54.         'agreetext': 'Sí',
  55.         'declinetext': 'No'
  56.     }
  57.  
  58.     return {
  59.         get: function(key) {
  60.             return config[key];
  61.         },
  62.         set: function(key, val) {
  63.             if( typeof key === 'string' ) {
  64.                 config[key] = val;
  65.             } else {
  66.                 config = CookieTool.Utils.extend(config, key);
  67.             }
  68.         }
  69.     }
  70. }());
  71.  
  72. /**
  73.  * Event API for customisation
  74.  */
  75. CookieTool.Event = (function() {
  76.     /** Where the callbacks are stored */
  77.     var events = {};
  78.     return {
  79.         /**
  80.          * Add an event listener
  81.          * @param {String} name the identifier
  82.          * @param {Function} callback
  83.          * @return undefined
  84.          */
  85.         on: function(name, callback) {
  86.             if( events[name] === undefined ) {
  87.                 events[name] = [];
  88.             }
  89.             if( typeof callback === 'function' ) {
  90.                 events[name].push(callback);
  91.             }
  92.         },
  93.         /**
  94.          * Trigger all event listeners for an identifier
  95.          * @param {String} name the identifier
  96.          * @return undefined
  97.          */
  98.         trigger: function(name) {
  99.             var cbs = events[name],
  100.                 i = 0,
  101.                 len;
  102.  
  103.             if( ! cbs ) {
  104.                 return;
  105.             }
  106.             len = cbs.length;
  107.             for (; i < len; i++) {
  108.                 cbs[i]();
  109.             }
  110.         }
  111.     }
  112. }());
  113.  
  114.  
  115. /**
  116.  * Cookie functions
  117.  */
  118. CookieTool.Cookie = {
  119.     /**
  120.      * Get a cookie value
  121.      * @param {String} key
  122.      * @return {String} the value
  123.      */
  124.     get: function(key) {
  125.         return decodeURIComponent(document.cookie.replace(new RegExp("(?:(?:^|.*;)\\s*" + encodeURIComponent(key).replace(/[\-\.\+\*]/g, "\\$&") + "\\s*\\=\\s*([^;]*).*$)|^.*$"), "$1")) || null;
  126.     },
  127.  
  128.     /**
  129.      * Set a cookie value
  130.      * @param {String} key
  131.      * @param {String} value
  132.      * @param {Number} days
  133.      * @param {String} domain
  134.      * @param {String} path
  135.      */
  136.     set: function(key, value, days, domain, path) {
  137.         var cookie = key + "=" + encodeURIComponent(value),
  138.             date;
  139.         if (days) {
  140.             date = new Date();
  141.             date.setTime(date.getTime()+(days*24*60*60*1000));
  142.             cookie += "; expires="+date.toGMTString();
  143.         }
  144.         if ( domain ) {
  145.             cookie += "; domain=" + domain
  146.         }
  147.         if( ! path ) {
  148.             path = "/";
  149.         }
  150.         cookie +=  "; path=" + path;
  151.         document.cookie = cookie;
  152.     },
  153.  
  154.     /**
  155.      * Delete a cookie
  156.      * @param {String} key
  157.      * @param {String} domain necessary for GA cookies
  158.      */
  159.     remove: function(key, domain) {
  160.         CookieTool.Cookie.set(key,"",-1, domain);
  161.     }
  162. }
  163.  
  164. /**
  165.  * Storage functions (HTML5 localStorage based) (permanent storage)
  166.  */
  167. if( window.localStorage ) {
  168.     CookieTool.Storage = {
  169.         /**
  170.          * Get a stored value
  171.          * @param {String} key
  172.          * @return {String} the value
  173.          */
  174.         get: function(key) {
  175.             return window.localStorage.getItem(key);
  176.         },
  177.         /**
  178.          * Set a value
  179.          * @param {String} key
  180.          * @param {String} value
  181.          */
  182.         set: function(key, value) {
  183.             return window.localStorage.setItem(key, value);
  184.         },
  185.         /**
  186.          * Delete a stored value
  187.          * @param {String} key
  188.          */
  189.         remove: function(key) {
  190.             return window.localStorage.removeItem(key);
  191.         }
  192.     }
  193. } else {
  194.     // Cookie based storage
  195.     CookieTool.Storage = CookieTool.Cookie;
  196. }
  197.  
  198. /**
  199.  * Main API
  200.  */
  201. CookieTool.API = {
  202.     /**
  203.      * Some status codes
  204.      */
  205.     statuses: {
  206.         'AGREE': '1',
  207.         'DECLINE': '0',
  208.         'UNDETERMINED': null
  209.     },
  210.     /**
  211.      * Set/get the current status of tracking
  212.      */
  213.     status: function(value) {
  214.         if( value === undefined ) {
  215.             return CookieTool.Storage.get('ctstatus');
  216.         }
  217.         if( CookieTool.API.statuses[value] ) {
  218.             return CookieTool.Storage.set('ctstatus', CookieTool.API.statuses[value], 365);
  219.         }
  220.         return CookieTool.Storage.set('ctstatus', value, 365);
  221.     },
  222.  
  223.     /**
  224.      * Ask for cookie consenting
  225.      */
  226.     ask: function() {
  227.         var message,
  228.             status,
  229.             body = document.body;
  230.         // Already agreed
  231.         if( CookieTool.API.status() === CookieTool.API.statuses.AGREE ) {
  232.             return CookieTool.API.agree();
  233.         }
  234.  
  235.         if( CookieTool.API.status() === CookieTool.API.statuses.DECLINE ) {
  236.             return CookieTool.API.decline();
  237.         }
  238.  
  239.         message = document.createElement('div');
  240.         message.className = 'cookietool-message cookietool-message-' + CookieTool.Config.get('position');
  241.         body.className += ' cookietool';
  242.         // No overcomplications with event listeners
  243.         message.onclick = function(e) {
  244.             var e = e || window.event,
  245.                 target = e.target || e.srcElement,
  246.                 action = target.getAttribute('data-action');
  247.             if( action && CookieTool.API[action] ) {
  248.                 CookieTool.API[action]();
  249.                 if( e.preventDefault ) {
  250.                     e.preventDefault();
  251.                 } else {
  252.                     e.returnValue = false;
  253.                 }
  254.                 message.parentNode.removeChild(message);
  255.                 body.className = body.className.replace(/\bcookietool\b/, '');
  256.                 return false;
  257.             }
  258.         }
  259.  
  260.         // onclick="" in <button>'s to fix event delegation in Safari for iPhone: http://www.quirksmode.org/blog/archives/2010/09/click_event_del.html
  261.         message.innerHTML = '<p>' + CookieTool.Config.get('message').replace(/\{\{link\}\}/g, CookieTool.Config.get('link')) + '</p><button data-action="agree" onclick="">' + CookieTool.Config.get('agreetext') + '</button> <button data-action="decline" onclick="">' + CookieTool.Config.get('declinetext') + '</button>';
  262.         body.appendChild(message);
  263.     },
  264.  
  265.     /**
  266.      * Assume implied agreement
  267.      * Note that you'll need at least somewhere in your page a link with a decline option (eg: <button onclick="CookieTool.API.decline()">I don't want cookies</button>)
  268.      */
  269.     impliedAgreement: function() {
  270.         var status = CookieTool.API.status();
  271.         switch(status) {
  272.             case CookieTool.API.statuses.DECLINE:
  273.                 CookieTool.API.decline();
  274.                 break;
  275.             // case CookieTool.API.statuses.UNDETERMINED:
  276.             // case CookieTool.API.statuses.AGREE:
  277.             default:
  278.                 CookieTool.API.agree();
  279.         }
  280.     },
  281.  
  282.     displaySettings: function(container) {
  283.         var status = CookieTool.API.status();
  284.         if( ! container ) {
  285.             return;
  286.         }
  287.  
  288.         container.className += ' cookietool-settings';
  289.         container.onclick = function(e) {
  290.             var e = e || window.event,
  291.                 target = e.target || e.srcElement,
  292.                 action = target.getAttribute('data-action');
  293.                 console.log();
  294.             if( action && CookieTool.API[action] ) {
  295.                 CookieTool.API[action]();
  296.                 CookieTool.API.displaySettings(container);
  297.                 if( e.preventDefault ) {
  298.                     e.preventDefault();
  299.                 } else {
  300.                     e.returnValue = false;
  301.                 }
  302.                 return false;
  303.             }
  304.         }
  305.  
  306.         if( status === CookieTool.API.statuses.AGREE ) {
  307.             container.innerHTML = 'Actualmente <strong>aceptas</strong> el uso de cookies en el sitio. <a role="button" data-action="decline" href="#">Pulsa aquí para no permitir cookies</a>';
  308.         } else if ( status === CookieTool.API.statuses.DECLINE ) {
  309.             container.innerHTML = 'Actualmente <strong>no aceptas</strong> el uso de cookies en el sitio. <a role="button" data-action="agree" href="#">Pulsa aquí para permitir cookies</a>'
  310.         } else {
  311.        
  312.     },
  313.     /**
  314.      * Agree
  315.      */
  316.      agree: function() {
  317.         CookieTool.API.status('AGREE');
  318.         CookieTool.Event.trigger('agree');
  319.      },
  320.  
  321.      /**
  322.       * Decline
  323.       */
  324.      decline: function() {
  325.         CookieTool.API.status('DECLINE');
  326.         CookieTool.Event.trigger('decline');
  327.      }
  328. }
  329.  
  330. /**
  331.  * Default id for settings, allows to put the script at the footer with no worries
  332.  */
  333.  if( document.getElementById('cookietool-settings') ) {
  334.     CookieTool.API.displaySettings(document.getElementById('cookietool-settings'));
  335.  }
  336.  
  337.  
  338. /**
  339.  * Default behaviour on agree: Load google analytics and adsense if present
  340.  */
  341. CookieTool.Event.on('agree', function() {
  342.     if( window.adsbygoogle ) {
  343.         CookieTool.Utils.loadScript('http://pagead2.googlesyndication.com/pagead/js/adsbygoogle.js');
  344.     }
  345.     if( window._gaq ) {
  346.         CookieTool.Utils.loadScript(('https:' == document.location.protocol ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js');
  347.     } else if ( window.ga ) {
  348.         CookieTool.Utils.loadScript('//wwww.google-analytics.com/analytics.js');
  349.     }
  350. });
  351.  
  352. /**
  353.  * Default behaviour on decline: Delete GA cookies
  354.  */
  355.  CookieTool.Event.on('decline', function() {
  356.     var cookiestodelete = ['__utma', '__utmb', '__utmc', '__utmz', '__utmv'],
  357.         i = 0,
  358.         len = cookiestodelete.length,
  359.         domain = window.location.hostname;
  360.     if( (/^www\./).test(domain) ) {
  361.         domain = domain.substring(4);
  362.     }
  363.  
  364.     for( ; i < len; i++) {
  365.         CookieTool.Cookie.remove(cookiestodelete[i], domain);
  366.     }
  367. });
  #4 (permalink)  
Antiguo 25/09/2014, 11:41
Colaborador
 
Fecha de Ingreso: septiembre-2013
Ubicación: España
Mensajes: 3.648
Antigüedad: 10 años, 7 meses
Puntos: 578
Respuesta: De casualidad alguien tiene codigo de cookies?

No es necesario todo ese código ni librerías para establecer una simple cookie

Código Javascript:
Ver original
  1. if (document.cookie.indexOf("visitado") < 0){
  2.   expire = new Date();
  3.   expire.setTime(Date.now()+(60*60*24*1000)); // 24 horas = 1 día
  4.   document.cookie = "visitado=1; expires=" + expire.toUTCString();
  5.   alert("Este mensaje se mostrará de nuevo mañana.");
  6. }

También se podría hacer con localStorage, pero así me parece conveniente
  #5 (permalink)  
Antiguo 26/09/2014, 02:47
 
Fecha de Ingreso: agosto-2014
Mensajes: 294
Antigüedad: 9 años, 7 meses
Puntos: 4
Respuesta: De casualidad alguien tiene codigo de cookies?

Muchas Gracias!

Última edición por yopmail; 26/09/2014 a las 04:16
  #6 (permalink)  
Antiguo 26/09/2014, 04:16
 
Fecha de Ingreso: agosto-2014
Mensajes: 294
Antigüedad: 9 años, 7 meses
Puntos: 4
Respuesta: De casualidad alguien tiene codigo de cookies?

Muchisimas Gracias! una pregunta como podria cambiar la alerta por un div con ID ?

Muchisimas Gracias por el aporte +1

Cita:
Iniciado por PHPeros Ver Mensaje
No es necesario todo ese código ni librerías para establecer una simple [URL="https://developer.mozilla.org/es/docs/DOM/document.cookie"]cookie[/URL]

Código Javascript:
Ver original
  1. if (document.cookie.indexOf("visitado") < 0){
  2.   expire = new Date();
  3.   expire.setTime(Date.now()+(60*60*24*1000)); // 24 horas = 1 día
  4.   document.cookie = "visitado=1; expires=" + expire.toUTCString();
  5.   alert("Este mensaje se mostrará de nuevo mañana.");
  6. }

También se podría hacer con localStorage, pero así me parece conveniente
  #7 (permalink)  
Antiguo 26/09/2014, 08:37
Colaborador
 
Fecha de Ingreso: septiembre-2013
Ubicación: España
Mensajes: 3.648
Antigüedad: 10 años, 7 meses
Puntos: 578
Respuesta: De casualidad alguien tiene codigo de cookies?

Me alegro de que te haya servido

Cita:
Iniciado por yopmail
como podria cambiar la alerta por un div con ID?
Eso ya sería obtener el elemento, y añadirle el texto con la propiedad textContent, por poner un ejemplo.
  #8 (permalink)  
Antiguo 26/09/2014, 09:34
 
Fecha de Ingreso: agosto-2014
Mensajes: 294
Antigüedad: 9 años, 7 meses
Puntos: 4
Respuesta: De casualidad alguien tiene codigo de cookies?

De nuevo muchas gracias por tu ayuda! pero estoy tan verde que no tengo ni idea de ponerlo, he probado varias formas ademas he buscado ejemplos en internet pero de ninguna de las formas me ha funcionado... es lo que tengo:

Código HTML:
 <script type="text/javascript">
if (document.cookie.indexOf("visitado") &lt; 0){
  expire = new Date();
  expire.setTime(Date.now()+(60*60*24*1000)); // 24 horas = 1 día
  document.cookie = "visitado=1; expires=" + expire.toUTCString();
}
var text = document.getElementById("sb-container").textContent;
 element = document.getElementById("sb-container");



</script> 

Si puedes echarme un cable estaria genial, si no, no pasa nada me has ayudado mucho!! +1





Cita:
Iniciado por PHPeros Ver Mensaje
Me alegro de que te haya servido



Eso ya sería [URL="https://developer.mozilla.org/en-US/docs/Web/API/document.getElementById"]obtener el elemento[/URL], y añadirle el texto con la propiedad [URL="https://developer.mozilla.org/es/docs/DOM/Node.textContent"]textContent[/URL], por poner un ejemplo.
  #9 (permalink)  
Antiguo 26/09/2014, 10:28
Colaborador
 
Fecha de Ingreso: septiembre-2013
Ubicación: España
Mensajes: 3.648
Antigüedad: 10 años, 7 meses
Puntos: 578
Respuesta: De casualidad alguien tiene codigo de cookies?

Código HTML:
Ver original
  1. <script type="text/javascript">
  2. if (document.cookie.indexOf("visitado") < 0){
  3.  expire = new Date();
  4.  expire.setTime(Date.now()+(60*60*24*1000)); // 24 horas = 1 día
  5.  document.cookie = "visitado=1; expires=" + expire.toUTCString();
  6.  var element = document.getElementById("sb-container");
  7.  element.textContent = "El texto que quieres mostrar.";
  8. }
  9.  

O también puedes crearlo y añadirlo con appendChild...

Última edición por PHPeros; 27/09/2014 a las 03:40
  #10 (permalink)  
Antiguo 26/09/2014, 15:58
 
Fecha de Ingreso: agosto-2014
Mensajes: 294
Antigüedad: 9 años, 7 meses
Puntos: 4
Respuesta: De casualidad alguien tiene codigo de cookies?

Hola de nuevo, creo que ni un año consigo que funcione xD me suena todo a chino... hay alguna forma de contratarte para que me hagas el codigo deseado?

Gracias de nuevo +1

Cita:
Iniciado por PHPeros Ver Mensaje
Código HTML:
Ver original
  1. <script type="text/javascript">
  2. if (document.cookie.indexOf("visitado") < 0){
  3.  expire = new Date();
  4.  expire.setTime(Date.now()+(60*60*24*1000)); // 24 horas = 1 día
  5.  document.cookie = "visitado=1; expires=" + expire.toUTCString();
  6. }
  7.  
  8. var element = document.getElementById("sb-container");
  9.  
  10. element.textContent = "El texto que quieres mostrar.";
  11.  

O también puedes crearlo y añadirlo con appendChild...
  #11 (permalink)  
Antiguo 27/09/2014, 03:42
Colaborador
 
Fecha de Ingreso: septiembre-2013
Ubicación: España
Mensajes: 3.648
Antigüedad: 10 años, 7 meses
Puntos: 578
Respuesta: De casualidad alguien tiene codigo de cookies?

Error mío de no meterlo en el if:

Código Javascript:
Ver original
  1. if (document.cookie.indexOf("visitado") < 0){
  2.   expire = new Date();
  3.   expire.setTime(Date.now()+(60*60*24*1000)); // 24 horas = 1 día
  4.   document.cookie = "visitado=1; expires=" + expire.toUTCString();
  5.   var element = document.getElementById("sb-container");
  6.   element.textContent = "El texto que quieres mostrar.";
  7. }
  #12 (permalink)  
Antiguo 28/09/2014, 04:10
(Desactivado)
 
Fecha de Ingreso: enero-2013
Mensajes: 289
Antigüedad: 11 años, 2 meses
Puntos: 10
Respuesta: De casualidad alguien tiene codigo de cookies?

En esta web te puedes descargar una barra que te permite aceptar o rechazar las cookies:

http://cookiecuttr.com/

nota: creo que el descargable le falta un archivo (jquery.cookie.js), con lo cual deberás copiar el código de este archivo de la misma página web.

Etiquetas: funcion, jquery
Atención: Estás leyendo un tema que no tiene actividad desde hace más de 6 MESES, te recomendamos abrir un Nuevo tema en lugar de responder al actual.
Respuesta




La zona horaria es GMT -6. Ahora son las 19:03.