zl程序教程

您现在的位置是:首页 >  前端

当前栏目

javascript设置cookie高级篇可跨域访问

JavaScriptCookie跨域 设置 访问 高级
2023-09-11 14:14:50 时间

 推荐使用:

//根据名称获取Cookie
function getCookie(cname) {
    var name = cname + "=";
    var ca = document.cookie.split(';');
    for (var i = 0; i < ca.length; i++) {
        var c = ca[i].trim();
        if (c.indexOf(name) == 0) return c.substring(name.length, c.length);
    }
    return null;
};

//设置Cookie; 参数cname名称,cvalue值,exdays天数
function setCookie(cname, cvalue, exdays) {
    var d = new Date();
    d.setTime(d.getTime() + (exdays * 24 * 60 * 60 * 1000));
    var expires = "expires=" + d.toGMTString();
    document.cookie = cname + "=" + cvalue + "; " + expires + ";path=/;domain=.xxxxx.com";
};
//使用时一定要修改 .xxxxx.com 为你的域名,  如www.baidu.com 改为.baidu.com

 

 常规操作

参考:JavaScript Cookie | 菜鸟教程

function setCookie(cname,cvalue,exdays){
    var d = new Date();
    d.setTime(d.getTime()+(exdays*24*60*60*1000));
    var expires = "expires="+d.toGMTString();
    document.cookie = cname+"="+cvalue+"; "+expires;
}
function getCookie(cname){
    var name = cname + "=";
    var ca = document.cookie.split(';');
    for(var i=0; i<ca.length; i++) {
        var c = ca[i].trim();
        if (c.indexOf(name)==0) { return c.substring(name.length,c.length); }
    }
    return "";
}
function checkCookie(){
    var user=getCookie("username");
    if (user!=""){
        alert("欢迎 " + user + " 再次访问");
    }
    else {
        user = prompt("请输入你的名字:","");
          if (user!="" && user!=null){
            setCookie("username",user,30);
        }
    }
}

跨域访问cookie (仅支持二级域名)

参考:javascript跨域设置cookie(二级域名)_xuebingnan的博客-CSDN博客

function setCookie(c_name, value, expiredays) {
		var exdate = new Date();
		exdate.setDate(exdate.getDate() + expiredays);
		document.cookie = c_name + "=" + escape(value) + ((expiredays == null) ? "" : ";expires=" + exdate.toGMTString() + ";path=/;domain=.testdomain.com")
	}

	var AdTime = new Date(); 
	if (AdTime != "") {

		setCookie("AdTime", AdTime, 1);
	}

延伸阅读

jQuery Cookie 插件

摘自:jQuery Cookie 插件 | 菜鸟教程

Query 可以通过 jquery.cookie.js 插件来操作 Cookie。

官方地址jQuery Cookie | jQuery Plugin Registry

Github 地址https://github.com/carhartl/jquery-cookie

使用 jquery.cookie.js 之前需要先引入 jQuery:

<script src="/path/to/jquery.min.js"></script>
<script src="/path/to/jquery.cookie.js"></script>

我们可以使用第三方资源库引入这两个文件:

<script src="https://cdn.staticfile.org/jquery/3.4.0/jquery.min.js"></script>
<script src="https://cdn.staticfile.org/jquery-cookie/1.4.1/jquery.cookie.min.js"></script>

使用方法

创建 cookie:

$.cookie('name', 'value');

如果未指定过期时间,则会在关闭浏览器或过期。

创建 cookie,并设置 7 天后过期:

$.cookie('name', 'value', { expires: 7 });

创建 cookie,并设置 cookie 的有效路径,路径为网站的根目录:

$.cookie('name', 'value', { expires: 7, path: '/' });

注:在默认情况下,只有设置 cookie 的网页才能读取该 cookie。如果想让一个页面读取另一个页面设 置的cookie,必须设置 cookie 的路径。cookie 的路径用于设置能够读取 cookie 的顶级目录。将这 个路径设置为网站的根目录,可以让所有网页都能互相读取 cookie (一般不要这样设置,防止出现冲突)。

读取 cookie:

$.cookie('name'); // => "value"
$.cookie('nothing'); // => undefined

读取所有的 cookie 信息:

$.cookie(); // => { "name": "value" }

删除 cookie:

// cookie 删除成功返回 true,否则返回 false
$.removeCookie('name'); // => true
$.removeCookie('nothing'); // => false 
 
// 写入使用了 path时,读取也需要使用相同的属性 (path, domain) 
$.cookie('name', 'value', { path: '/' });
 
// 以下代码【删除失败】
$.removeCookie('name'); // => false
// 以下代码【删除成功】
$.removeCookie('name', { path: '/' }); // => true

注意:删除 cookie 时,必须传递用于设置 cookie 的完全相同的路径,域及安全选项。

$(document).ready(function(){
  $.cookie('name', 'runoob');  // 创建 cookie
  name = $.cookie('name');     // 读取 cookie
  $("#test").text(name);
  $.cookie('name2', 'runoob2', { expires: 7, path: '/' });
  name2 = $.cookie('name2');
  $("#test2").text(name2);
});

执行完后,我们可以在浏览器中查看 Cookie 信息,如下图所示:

参数说明

raw

默认值:false。

默认情况下,读取和写入 cookie 的时候自动进行编码和解码(使用 encodeURIComponent 编码,decodeURIComponent 解码)。要关闭这个功能设置 raw:true 即可:

$.cookie.raw = true;

json

设置 cookie 的数据使用 json 存储与读取,这时就不需要使用 JSON.stringify 和 JSON.parse 了。

$.cookie.json = true;

expires

定义 cookie 的有效时间,值可以是一个数字(从创建 cookie 时算起,以天为单位)或一个 Date 对象。如果省略,那么创建的 cookie 是会话 cookie,将在用户退出浏览器时被删除。

expires: 365

path

默认情况:只有设置 cookie 的网页才能读取该 cookie。

定义 cookie 的有效路径。默认情况下, 该参数的值为创建 cookie 的网页所在路径(标准浏览器的行为)。

如果你想在整个网站中访问这个 cookie 需要这样设置有效路径:path: '/'。如果你想删除一个定义了有效路径的 cookie,你需要在调用函数时包含这个路径:

path: '/'
$.cookie('the_cookie', null,{ path: '/' });

domain

默认值:创建 cookie 的网页所拥有的域名。

domain: 'example.com'

secure

默认值:false。如果为 true,cookie 的传输需要使用安全协议(HTTPS)。

secure: true

源码

/*!
 * jQuery Cookie Plugin v1.4.1
 * https://github.com/carhartl/jquery-cookie
 *
 * Copyright 2006, 2014 Klaus Hartl
 * Released under the MIT license
 */
(function (factory) {
	if (typeof define === 'function' && define.amd) {
		// AMD (Register as an anonymous module)
		define(['jquery'], factory);
	} else if (typeof exports === 'object') {
		// Node/CommonJS
		module.exports = factory(require('jquery'));
	} else {
		// Browser globals
		factory(jQuery);
	}
}(function ($) {

	var pluses = /\+/g;

	function encode(s) {
		return config.raw ? s : encodeURIComponent(s);
	}

	function decode(s) {
		return config.raw ? s : decodeURIComponent(s);
	}

	function stringifyCookieValue(value) {
		return encode(config.json ? JSON.stringify(value) : String(value));
	}

	function parseCookieValue(s) {
		if (s.indexOf('"') === 0) {
			// This is a quoted cookie as according to RFC2068, unescape...
			s = s.slice(1, -1).replace(/\\"/g, '"').replace(/\\\\/g, '\\');
		}

		try {
			// Replace server-side written pluses with spaces.
			// If we can't decode the cookie, ignore it, it's unusable.
			// If we can't parse the cookie, ignore it, it's unusable.
			s = decodeURIComponent(s.replace(pluses, ' '));
			return config.json ? JSON.parse(s) : s;
		} catch(e) {}
	}

	function read(s, converter) {
		var value = config.raw ? s : parseCookieValue(s);
		return $.isFunction(converter) ? converter(value) : value;
	}

	var config = $.cookie = function (key, value, options) {

		// Write

		if (arguments.length > 1 && !$.isFunction(value)) {
			options = $.extend({}, config.defaults, options);

			if (typeof options.expires === 'number') {
				var days = options.expires, t = options.expires = new Date();
				t.setMilliseconds(t.getMilliseconds() + days * 864e+5);
			}

			return (document.cookie = [
				encode(key), '=', stringifyCookieValue(value),
				options.expires ? '; expires=' + options.expires.toUTCString() : '', // use expires attribute, max-age is not supported by IE
				options.path    ? '; path=' + options.path : '',
				options.domain  ? '; domain=' + options.domain : '',
				options.secure  ? '; secure' : ''
			].join(''));
		}

		// Read

		var result = key ? undefined : {},
			// To prevent the for loop in the first place assign an empty array
			// in case there are no cookies at all. Also prevents odd result when
			// calling $.cookie().
			cookies = document.cookie ? document.cookie.split('; ') : [],
			i = 0,
			l = cookies.length;

		for (; i < l; i++) {
			var parts = cookies[i].split('='),
				name = decode(parts.shift()),
				cookie = parts.join('=');

			if (key === name) {
				// If second argument (value) is a function it's a converter...
				result = read(cookie, value);
				break;
			}

			// Prevent storing a cookie that we couldn't decode.
			if (!key && (cookie = read(cookie)) !== undefined) {
				result[name] = cookie;
			}
		}

		return result;
	};

	config.defaults = {};

	$.removeCookie = function (key, options) {
		// Must not alter options, thus extending a fresh object...
		$.cookie(key, '', $.extend({}, options, { expires: -1 }));
		return !$.cookie(key);
	};

}));